Esempio n. 1
0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var currentTime    = DateTime.UtcNow;
            var timeDifference = DateTimeSpan.CompareDates(currentTime, (DateTime)value);

            if (timeDifference.Years > 0)
            {
                return(string.Format("{0} Year{1} ago", timeDifference.Years, timeDifference.Years > 1 ? "s" : ""));
            }
            else if (timeDifference.Months > 0)
            {
                return(string.Format("{0} Month{1} ago", timeDifference.Months, timeDifference.Months > 1 ? "s" : ""));
            }
            else if (timeDifference.Days > 0)
            {
                return(string.Format("{0} Day{1} ago", timeDifference.Days, timeDifference.Days > 1 ? "s" : ""));
            }
            else if (timeDifference.Hours > 0)
            {
                return(string.Format("{0} Hour{1} ago", timeDifference.Hours, timeDifference.Hours > 1 ? "s" : ""));
            }
            else if (timeDifference.Minutes > 0)
            {
                return(string.Format("{0} Minute{1} ago", timeDifference.Minutes, timeDifference.Minutes > 1 ? "s" : ""));
            }
            else
            {
                return("Just Now");
            }
        }
Esempio n. 2
0
        public void Execute(IJobExecutionContext context)
        {
            DateTime today = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0);

            using (DataContext _db = new DataContext())
            {
                _db.Database.CommandTimeout = 6000;
                using (DbContextTransaction tran = _db.Database.BeginTransaction(System.Data.IsolationLevel.Serializable))
                {
                    try
                    {
                        foreach (var card in _db.Cards.Where(c => c.CardStatus != CardStatus.Canceled && c.CardStatus != CardStatus.Blocked && c.CardStatus != CardStatus.Paused))
                        {
                            var dateSpan = DateTimeSpan.CompareDates(card.Tdate, DateTime.Now);
                            if (dateSpan.Months == 0 && dateSpan.Days == 1)
                            {
                                card.LastPauseType      = 0;
                                card.PauseFreeMonthUsed = false;
                                _db.Entry(card).State   = System.Data.Entity.EntityState.Modified;
                                _db.SaveChanges();
                            }
                        }

                        tran.Commit();
                    }
                    catch (Exception)
                    {
                        tran.Rollback();
                    }
                }
            }
        }
        public static bool HasEnoughTransactions(List <Item> list, Brand brand, string model)
        {
            List <Item> transactions = list.Where(m => m.Brand == brand).Where(m => m.Model == model).ToList();


            if (transactions.Count() <= 1 || transactions == null)
            {
                return(false);
            }

            DateTime earliestDate    = transactions.Select(m => m.Date).Min();
            DateTime latestDate      = transactions.Select(m => m.Date).Max();
            var      datetime        = DateTimeSpan.CompareDates(earliestDate, latestDate);
            int      monthDifference = datetime.Years * 12 + datetime.Months;

            System.Diagnostics.Debug.WriteLine($"DATE: {earliestDate.ToString()} - {latestDate.ToString()} = {monthDifference}");

            if (monthDifference < 24)
            {
                return(false);
            }
            if (transactions.Count() < ((monthDifference / 100) * 90))
            {
                return(false);
            }

            return(true);
        }
        private List <int> AutogenerateMissingDataIfPossible(List <int> selectedPhoneIds, int months = 3)
        {
            List <int> eligibleIds = selectedPhoneIds;

            DateTime today        = DateTime.Today;
            int      currentMonth = DateTime.Today.Month;
            int      currentYear  = DateTime.Today.Year;

            foreach (int id in selectedPhoneIds)
            {
                Brand  selectedBrand = Hardware.FirstOrDefault(x => x.ConfigId == id).Brand;
                string selectedModel = Hardware.FirstOrDefault(x => x.ConfigId == id).Model;

                DateTime latestDate      = Phones.Where(x => x.Brand == selectedBrand && x.Model == selectedModel).Max(x => x.Date);
                var      datetime        = DateTimeSpan.CompareDates(latestDate, today);
                int      monthDifference = datetime.Years * 12 + datetime.Months;

                // Remove id if latest date cannot be found or the gap is too big
                if (latestDate == null || monthDifference > 3)
                {
                    eligibleIds.RemoveAll(x => x == id);
                    Errors.Add($"{selectedBrand} {selectedModel} - Data for the last {monthDifference} months is unavailable.");
                    Errors = Errors.Distinct().ToList();
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"Generating data");

                    TimeSeriesPrediction prediction = new TimeSeriesPrediction(Phones, selectedBrand, selectedModel);
                    prediction.GenerateFutureForecast(monthDifference);
                }
            }

            return(new List <int>());
        }
        public List <ChartItem> DrawChart(List <int> hardwareId)
        {
            List <ChartItem> allCharts = new List <ChartItem>();


            // Itterates through all passed id
            for (int i = 0; i < hardwareId.Count; i++)
            {
                // Find brand and model corresponding to id
                var currentBrand = Hardware.FirstOrDefault(m => m.ConfigId == hardwareId[i]).Brand;
                var currentModel = Hardware.FirstOrDefault(m => m.ConfigId == hardwareId[i]).Model;

                // The constructor already removes phones where gap between last transaction and today is more than ALLOWED_TRANSACTION_GAP_MONTHS
                // I don't need to validate here, it will always be less then that specified month gap.
                DateTime today           = DateTime.Today;
                DateTime latestDate      = Phones.Where(x => x.Brand == currentBrand && x.Model == currentModel).Max(x => x.Date);
                var      datetime        = DateTimeSpan.CompareDates(latestDate, today);
                int      monthDifference = datetime.Years * 12 + datetime.Months;

                // If there are enough transactions -> draws a chart and computers a forecasted price
                allCharts.Add(new ChartItem
                {
                    Label       = $"{currentBrand.ToString()} {currentModel}",
                    Fill        = false,
                    BorderWidth = 1,
                    // Computers price forecast. Returns a list of objects containing purchase date and price.
                    LstData = ComputeForecast(hardwareId[i], (FutureForecastMonths + monthDifference))
                });
            }

            return(allCharts);
        }
Esempio n. 6
0
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var currentTime = DateTime.UtcNow;

            if (((DateTime)value).Year == 1)
            {
                return("the dawn of reddit");
            }
            var timeDifference = DateTimeSpan.CompareDates(currentTime, (DateTime)value);

            if (timeDifference.Years > 0)
            {
                return(string.Format("{0} year{1} ago", timeDifference.Years, timeDifference.Years > 1 ? "s" : ""));
            }
            else if (timeDifference.Months > 0)
            {
                return(string.Format("{0} month{1} ago", timeDifference.Months, timeDifference.Months > 1 ? "s" : ""));
            }
            else if (timeDifference.Days > 0)
            {
                return(string.Format("{0} day{1} ago", timeDifference.Days, timeDifference.Days > 1 ? "s" : ""));
            }
            else if (timeDifference.Hours > 0)
            {
                return(string.Format("{0} hour{1} ago", timeDifference.Hours, timeDifference.Hours > 1 ? "s" : ""));
            }
            else if (timeDifference.Minutes > 0)
            {
                return(string.Format("{0} minute{1} ago", timeDifference.Minutes, timeDifference.Minutes > 1 ? "s" : ""));
            }
            else
            {
                return("just now");
            }
        }
Esempio n. 7
0
        public static string DiffForHumans(this DateTime dateTime)
        {
            var time = DateTimeSpan.CompareDates(dateTime, DateTime.UtcNow);

            if (time.Years != 0)
            {
                return($"{time.Years} years ago");
            }
            if (time.Months != 0)
            {
                return($"{time.Months} months ago");
            }
            if (time.Days != 0)
            {
                return($"{time.Days} days ago");
            }
            if (time.Hours != 0)
            {
                return($"{time.Hours} hours ago");
            }
            if (time.Minutes != 0)
            {
                return($"{time.Minutes} minutes ago");
            }
            return("Just now");
        }
Esempio n. 8
0
        private static int GetMonthDifference(DateTime date1, DateTime date2)
        {
            // Note: it doesn't matter which dates comes before the other.
            var dateSpan = DateTimeSpan.CompareDates(date1, date2);

            return((dateSpan.Years * 12) + dateSpan.Months);
        }
Esempio n. 9
0
        public List <ForecastResult> GenerateFutureForecast(int month = 12)
        {
            DateTime     today        = DateTime.Today;
            DateTime     lastDate     = m_observations.Max(x => x.Date);
            DateTimeSpan dateTimeSpan = DateTimeSpan.CompareDates(today, lastDate);
            int          difference   = (dateTimeSpan.Years * 12) + dateTimeSpan.Months;

            month += difference;

            for (int i = 0; i < month; i++)
            {
                // Adds new observation with date which is 1 month greater than the last object in m_observations;
                m_observations.Add(new Observation(m_observations[m_observations.Count - 1].Date.AddMonths(1)));
            }

            for (int i = 0; i < m_observations.Count; i++)
            {
                if (m_observations[i].Seasonality == null)
                {
                    m_observations[i].Seasonality = Algorithm.CalculateSeasonality(m_observations, i);
                    m_observations[i].Trend       = Algorithm.CalculateTrend(m_observations, i);
                    m_observations[i].Forecast    = Algorithm.CalculateForecast(m_observations, i);
                }
            }

            return(m_observations.Select(x => new ForecastResult(x.Date, x.Forecast.Value)).ToList());
        }
Esempio n. 10
0
        public List <ChartItem> DrawChart(List <int> hardwareId)
        {
            List <ChartItem> allCharts = new List <ChartItem>();

            for (int i = 0; i < hardwareId.Count; i++)
            {
                var currentBrand = Hardware.FirstOrDefault(x => x.ConfigId == hardwareId[i]).Brand;
                var currentModel = Hardware.FirstOrDefault(x => x.ConfigId == hardwareId[i]).Model;

                DateTime today           = DateTime.Today;
                DateTime latestDate      = Transactions.Where(x => x.Brand == currentBrand && x.Model == currentModel).Max(x => x.Date);
                var      datetime        = DateTimeSpan.CompareDates(latestDate, today);
                int      monthDifference = datetime.Years * 12 + datetime.Months;

                allCharts.Add(new ChartItem
                {
                    Label       = $"{currentBrand.ToString()} {currentModel}",
                    Fill        = false,
                    BorderWidth = 1,
                    LstData     = ComputeForecast(hardwareId[i], (12 + monthDifference))
                });
            }

            return(allCharts);
        }
Esempio n. 11
0
        private List <ChartTransaction> ComputeForecast(int id, int forecastMonths = 12)
        {
            List <ChartTransaction> transactions = new List <ChartTransaction>();

            Brand  currentBrand = Hardware.FirstOrDefault(x => x.ConfigId == id).Brand;
            string currentModel = Hardware.FirstOrDefault(x => x.ConfigId == id).Model;

            TimeSeriesPrediction prediction = new TimeSeriesPrediction(Transactions, currentBrand, currentModel);

            prediction.GenerateFutureForecast(forecastMonths);

            DateTime today = DateTime.Today;

            foreach (Phone p in prediction.PhoneCollection.Phones)
            {
                DateTime currentDate    = p.Date;
                var      datetime       = DateTimeSpan.CompareDates(currentDate, today);
                int      yearDifference = datetime.Years;

                if (yearDifference <= 2)
                {
                    this.AddTransactionToRecord(id, new ChartTransaction {
                        Date = p.Date, Price = p.Forecast.Value
                    });
                    transactions.Add(new ChartTransaction
                    {
                        Date  = p.Date,
                        Price = p.Forecast.Value
                    });
                }
            }

            return(transactions);
        }
Esempio n. 12
0
        protected override void Execute(CodeActivityContext context)
        {
            String DateS1 = Date1String.Get(context);
            String DateS2 = Date2String.Get(context);
            Dictionary <String, Int32> dict = new Dictionary <string, int>();
            String format = Format.Get(context);

            if (String.IsNullOrEmpty(format))
            {
                format = "dd/MM/yyyy";
            }
            DateTime DT1 = DateTime.ParseExact(DateS1, format, null);
            DateTime DT2 = DateTime.ParseExact(DateS2, format, null);

            DateTimeSpan dateSpan = DateTimeSpan.CompareDates(DT1, DT2);

            dict["Years"]        = dateSpan.Years;
            dict["Months"]       = dateSpan.Months;
            dict["Days"]         = dateSpan.Days;
            dict["Hours"]        = dateSpan.Hours;
            dict["Minutes"]      = dateSpan.Minutes;
            dict["Seconds"]      = dateSpan.Seconds;
            dict["Milliseconds"] = dateSpan.Milliseconds;

            Difference.Set(context, dict);
        }
Esempio n. 13
0
        /// <summary>
        ///     Obtiene los datos generales de los beneficiarios
        /// </summary>
        /// <param name="issstenumber">Numero de ISSSTE del derechohabiente a consultar</param>
        /// <returns>Datos generales de los beneficiarios</returns>
        public async Task <List <BeneficiarySipeInformation> > GetBeneficiariesByNoIsssteAsync(string issstenumber)
        {
            var token = GetToken();

            var baseAddress = ServiceBaseUrl + String.Format(BeneficiariesInfoUrl, issstenumber);

            var http = BuildHttpClient(baseAddress, token);

            var response = await http.GetAsync(baseAddress);

            response.EnsureSuccessStatusCode();

            var json = await response.Content.ReadAsStringAsync();

            var indirecto = JsonConvert.DeserializeObject <List <BeneficiarySipeInformation> >(json);

            foreach (var beneficiary in indirecto)
            {
                beneficiary.Age = DateTimeSpan.CompareDates(Convert.ToDateTime(beneficiary.BirthDate), DateTime.Now);

                beneficiary.AgeYears = beneficiary.Age.Years;
            }

            return(indirecto.OrderByDescending(o => o.BirthDate).ToList());
        }
Esempio n. 14
0
        /// <summary>
        ///     Obtiene los datos generales de un derechohabiente
        /// </summary>
        /// <param name="isssteNumber">Numero de ISSSTE del derechohabiente a consultar</param>
        /// <returns>Datos generales del derechohabiente</returns>
        public async Task <EntitleSipeInformation> GetEntitleByNoIsssteAsync(string isssteNumber)
        {
            var token = GetToken();

            var baseAddress = ServiceBaseUrl + String.Format(EntitleByNoIsssteInfoUrl, isssteNumber);

            var http = BuildHttpClient(baseAddress, token);

            var response = await http.GetAsync(baseAddress);

            response.EnsureSuccessStatusCode();

            var json = await response.Content.ReadAsStringAsync();

            var directo = JsonConvert.DeserializeObject <List <EntitleSipeInformation> >(json);

            var firstDirecto = directo.FirstOrDefault();

            if (firstDirecto != null)
            {
                firstDirecto.Age =
                    DateTimeSpan.CompareDates(Convert.ToDateTime(firstDirecto.BirthDate), DateTime.Now).Years;
            }

            return(firstDirecto);
        }
Esempio n. 15
0
        public async Task <List <RelativesSipeInformation> > GetBeneficiariesCIByNoIsssteAsync(string issstenumber)
        {
            var token = GetToken();

            var baseAddress = ServiceBaseUrl + String.Format(BeneficiariesCIInfoUrl, issstenumber);

            var http = BuildHttpClient(baseAddress, token);

            var response = await http.GetAsync(baseAddress);

            response.EnsureSuccessStatusCode();

            var json = await response.Content.ReadAsStringAsync();

            var indirecto = JsonConvert.DeserializeObject <List <RelativesSipeInformation> >(json);

            const int AGE_MINIMUM = 18;
            const int AGE_MAXIMUM = 25;

            var relativesList = new List <RelativesSipeInformation>();

            if (indirecto != null)
            {
                foreach (var relative in indirecto)
                {
                    if (relative.VersionKey.IsEmpty())
                    {
                        relative.Age = DateTimeSpan.CompareDates(Convert.ToDateTime(relative.BirthDate), DateTime.Now).Years;
                        relativesList.Add(relative);
                    }
                    else
                    {
                        relative.Age = DateTimeSpan.CompareDates(Convert.ToDateTime(relative.BirthDate), DateTime.Now).Years;

                        if (String.Equals(relative.VersionKey.ToUpper(), "P"))
                        {
                            relativesList.Add(relative);
                        }
                        else if (relative.Age < AGE_MINIMUM)
                        {
                            relativesList.Add(relative);
                        }
                        else if (relative.Age >= AGE_MINIMUM && relative.Age <= AGE_MAXIMUM &&
                                 String.Equals(relative.VersionKey.ToUpper(), "T"))
                        {
                            relativesList.Add(relative);
                        }
                    }
                }
            }

            return(indirecto.OrderByDescending(o => o.BirthDate).ToList());
        }
Esempio n. 16
0
        public void DateTimeYears()
        {
            //Arrange
            DateTime dt1 = new DateTime(2000, 1, 1);
            DateTime dt2 = new DateTime(2001, 1, 1);

            // Act
            var dts = DateTimeSpan.CompareDates(dt1, dt2).Years;

            // Assert
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(dts, 1);
        }
                private static double CalculateSuggestedPrice(List <Observation> observations, DateTime date)
                {
                    Observation previousTransaction;
                    Observation nextTransaction;

                    try
                    {
                        previousTransaction = observations
                                              .Where(i => i.Date < date)
                                              .OrderByDescending(i => i.Date)
                                              .FirstOrDefault();
                    }
                    catch
                    {
                        throw new Exception("Could not find previous transcation.");
                    }

                    try
                    {
                        nextTransaction = observations
                                          .Where(i => i.Date > date)
                                          .OrderByDescending(i => i.Date)
                                          .LastOrDefault();
                    }
                    catch
                    {
                        throw new Exception("Could not find next transaction.");
                    }

                    DateTime dateBefore = previousTransaction.Date;
                    DateTime dateAfter  = nextTransaction.Date;

                    if (dateBefore == dateAfter || dateBefore > dateAfter)
                    {
                        throw new Exception("Datetime mismatch");
                    }

                    DateTimeSpan dateTimeSpan    = DateTimeSpan.CompareDates(dateBefore, dateAfter);
                    int          monthDifference = (dateTimeSpan.Years * 12 + dateTimeSpan.Months);

                    if (!previousTransaction.Value.HasValue || !nextTransaction.Value.HasValue)
                    {
                        throw new Exception("Ambiguously priced transactions.");
                    }

                    // Stupidly named, but an observation keeps the numeric field that is being forecast
                    // as "Value". So, "Value.Value" force unwraps the optional double named Value.
                    double transactionValueBefore = previousTransaction.Value.Value;
                    double transactionValueAfter  = nextTransaction.Value.Value;

                    return(transactionValueBefore - ((transactionValueBefore - transactionValueAfter) / monthDifference));
                }
Esempio n. 18
0
        DateTime GetLastCalculationDate(DateTime lastPay)
        {
            DateTime compareTo = lastPay;
            DateTime now       = DateTime.Now;
            var      dateSpan  = DateTimeSpan.CompareDates(compareTo, now);
            //Console.WriteLine("Years: " + dateSpan.Years);
            //Console.WriteLine("Months: " + dateSpan.Months);
            //Console.WriteLine("Days: " + dateSpan.Days);
            // Console.WriteLine("Hours: " + dateSpan.Hours);
            // Console.WriteLine("Minutes: " + dateSpan.Minutes);
            // Console.WriteLine("Seconds: " + dateSpan.Seconds);
            // Console.WriteLine("Milliseconds: " + dateSpan.Milliseconds);
            int months = ((dateSpan.Years * 12) + dateSpan.Months);

            return(lastPay.AddMonths(months));
        }
Esempio n. 19
0
        private void btnGenerarReporte_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DateTime dInicio = Convert.ToDateTime(dtInicio.EditValue);
            DateTime dFin    = Convert.ToDateTime(dtFin.EditValue);
            int      result  = DateTime.Compare(dInicio, dFin);

            if (result < 1)
            {
                var dateSpan = DateTimeSpan.CompareDates(dInicio, dFin);
                CLS_Pedidos_Sucursales selped = new CLS_Pedidos_Sucursales();
                selped.Sucursal = Convert.ToInt32(cboSucursales.EditValue.ToString());
                decimal meses  = dateSpan.Months;
                decimal dias   = Convert.ToDecimal(dateSpan.Days) / 30;
                decimal tmeses = decimal.Round((meses + dias), 0);
                if (tmeses == 0)
                {
                    tmeses = 1;
                }
                txtMesesVenta.Text = tmeses.ToString();
                selped.MesesVenta  = Convert.ToInt32(tmeses);
                selped.FechaInicio = string.Format("{0}{1}{2} 00:00:00", dInicio.Year, DosCeros(dInicio.Month.ToString()), DosCeros(dInicio.Day.ToString()));
                selped.FechaFin    = string.Format("{0}{1}{2} 23:59:59", dFin.Year, DosCeros(dFin.Month.ToString()), DosCeros(dFin.Day.ToString()));
                MensajeCargando(1);
                selped.MtdGenerarPedidoSucursal();
                if (selped.Exito)
                {
                    if (selped.Datos.Rows.Count > 0)
                    {
                        dtgPedidos.DataSource = selped.Datos;
                        CalcularCampos();
                    }
                    else
                    {
                        XtraMessageBox.Show("No existe registros para mostrar");
                    }
                }
                else
                {
                    XtraMessageBox.Show(selped.Mensaje);
                }
                MensajeCargando(2);
            }
            else
            {
                XtraMessageBox.Show("La fecha de Inicio no puede ser mayor a la Fecha Fin");
            }
        }
        private List <ChartTransaction> ComputeForecast(int id, int forecastMonths = 12)
        {
            var asd = ContainsEnoughData(SelectedItems);

            // A ChartTransaction object contains date of purchase and price.
            List <ChartTransaction> transactions = new List <ChartTransaction>();

            // Find brand and model based on passed id
            Brand  selectedBrand = Hardware.FirstOrDefault(m => m.ConfigId == id).Brand;
            string selectedModel = Hardware.FirstOrDefault(m => m.ConfigId == id).Model;

            // Generates time series forecast.
            // RemoveUnforecastableIds method already checks if there are enough transactions to compute.
            TimeSeriesPrediction prediction = new TimeSeriesPrediction(Phones, selectedBrand, selectedModel);

            prediction.GenerateFutureForecast(forecastMonths);

            DateTime today = DateTime.Today;

            // Itterate through all objects
            foreach (Phone p in prediction.PhoneCollection.Phones)
            {
                DateTime currentDate    = p.Date;
                var      datetime       = DateTimeSpan.CompareDates(currentDate, today);
                int      yearDifference = datetime.Years;

                // Forecast is generated using ALL data
                // Chart only displays data from the last 2 years + the forecast
                if (yearDifference <= 2)
                {
                    // Adds to the List<Dict<int, ChartTrans>> so calculations can be done
                    // In order to find the best/worst future price
                    this.AddTransactionToRecord(id, new ChartTransaction {
                        Date = p.Date, Price = p.Forecast.Value
                    });
                    // Records their date and price.
                    transactions.Add(new ChartTransaction
                    {
                        Date  = p.Date,
                        Price = p.Forecast.Value
                    });
                }
            }

            return(transactions);
        }
Esempio n. 21
0
    protected void check_expiry(int[] ids, int count)
    {
        string        constring = ConfigurationManager.ConnectionStrings["Dairy_SolutionConnectionString"].ConnectionString;
        SqlConnection con       = new SqlConnection(constring);
        SqlCommand    cmd       = new SqlCommand();
        string        query     = "";
        bool          status    = false;

        for (int i = 0; i <= count; i++)
        {
            query           = "SELECT products.product_id, products.product_name, inventory_products.batch_id, inventory_products.quantity, inventory_products.expiry_date FROM products INNER JOIN inventory_products ON products.product_id = inventory_products.product_id WHERE products.product_id = '" + ids[i] + "'";
            cmd.Connection  = con;
            cmd.CommandText = query;
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            string        prod_name = "", batch_no = "", msg = "";

            while (dr.Read())
            {
                if (dr.HasRows)
                {
                    DateTime date     = Convert.ToDateTime(dr["expiry_date"]);
                    DateTime now      = DateTime.Now;
                    var      datespan = DateTimeSpan.CompareDates(date, now);
                    if (date > now)
                    {
                        if (datespan.Months <= 1)
                        {
                            prod_name = dr["product_name"].ToString();
                            batch_no  = dr["batch_id"].ToString();
                            msg       = "Product Name: " + prod_name + " Batch Number: " + batch_no + " Expiry date reaching! Months left: " + (datespan.Months + 1);
                            status    = true;
                        }// if months left are less than 2
                    }
                }
            }// end while loop
            con.Close();
            if (status == true)
            {
                check_notification(msg, "exp date");
            }
            status = false;
            msg    = "";
        }// end for loop
    }
Esempio n. 22
0
        double CalculateBalance(string amount, string rate, DateTime lastPay)
        {
            // Make sure we use types that hold decimal places
            double new_balance, ending_balance;
            double interest_paid, annual_rate, principle_paid, payment;

            ending_balance = Convert.ToDouble(amount);
            //(double)yearlyInterestRate / 100 / 12;
            annual_rate = Convert.ToDouble(rate);
            // Setup a counter to count payments
            int count = 1;
            //get months in between
            DateTime compareTo = lastPay;
            DateTime now       = DateTime.Now;
            var      dateSpan  = DateTimeSpan.CompareDates(compareTo, now);
            //Console.WriteLine("Years: " + dateSpan.Years);
            //Console.WriteLine("Months: " + dateSpan.Months);
            //Console.WriteLine("Days: " + dateSpan.Days);
            // Console.WriteLine("Hours: " + dateSpan.Hours);
            // Console.WriteLine("Minutes: " + dateSpan.Minutes);
            // Console.WriteLine("Seconds: " + dateSpan.Seconds);
            // Console.WriteLine("Milliseconds: " + dateSpan.Milliseconds);
            int months = ((dateSpan.Years * 12) + dateSpan.Months);

            // Get our standard payment which is 1/months of loan
            //payment = (ending_balance / months);
            //payment = Convert.ToDouble(monthly);
            while (count <= months)
            {
                new_balance = ending_balance;
                // Calculate interest by multiplying rate against balance
                interest_paid = new_balance * (annual_rate / 100 / 12.0);
                // Subtract interest from your payment
                // principle_paid = payment - interest_paid;
                // Subtract final payment from running balance
                ending_balance = new_balance + interest_paid;
                // If the balance remaining plus its interest is less than payment amount
                // Then print out 0 balance, the interest paid and that balance minus the interest will tell us
                // how much principle you paid to get to zero.

                count++;
            }
            return(ending_balance);
        }
Esempio n. 23
0
        private void populateAgreements(CustomerExtendedDetails detail)
        {
            CustomerExtendedDetailID     = detail.CustomerExtendedDetailID;
            AgreeToIhPolicyAndProcedures = false;
            AgreeToIhSaEnrollmentPolicy  = false;
            AgreeToIhESignNotice         = false;
            GracePeriodExpired           = false;

            DateTime date1 = DateTime.MinValue,
                     date4 = DateTime.MinValue,
                     date5 = DateTime.MinValue,
                     date6 = DateTime.MinValue;

            DateTime.TryParse(detail.Field1, out date1);
            DateTime.TryParse(detail.Field4, out date4);
            DateTime.TryParse(detail.Field5, out date5);
            DateTime.TryParse(detail.Field6, out date6);

            if (date1 >= AgreementsEffectiveDate)
            {
                AgreeToIhSaEnrollmentPolicy = true;
            }

            if (date4 >= AgreementsEffectiveDate)
            {
                AgreeToIhPolicyAndProcedures = true;
            }

            if (date5 >= AgreementsEffectiveDate)
            {
                AgreeToIhESignNotice = true;
            }

            if (!DateTime.MinValue.Equals(date6) &&
                (DateTimeSpan.CompareDates(DateTime.Now, date6).Days > GracePeriodDays ||
                 !GracePeriodDays.HasValue))
            {
                GracePeriodExpired = true;
            }
            else if (DateTime.MinValue.Equals(date6))
            {
                GracePeriodExpired = null;
            }
        }
Esempio n. 24
0
                public static bool HasEnoughTransactions(List <Observation> observations, PhoneModel?phone)
                {
                    if (phone == null)
                    {
                        return(false);
                    }

                    if (observations.Count <= 24 || observations == null)
                    {
                        return(false);
                    }

                    int      monthDifference = 0;
                    DateTime?earliestDate    = null;
                    DateTime?latestDate      = null;


                    if (observations.Count > 12)
                    {
                        earliestDate = observations.Select(x => x.Date).Min();
                        latestDate   = observations.Select(x => x.Date).Max();
                        DateTimeSpan datetimespan = DateTimeSpan.CompareDates(earliestDate.Value, latestDate.Value);
                        monthDifference = datetimespan.Years * 12 + datetimespan.Months;
                    }
                    else
                    {
                        return(false);
                    }

                    // At least two years of data must be present to compute forecast.
                    if (monthDifference < 24)
                    {
                        return(false);
                    }
                    // Checks for gaps. If the recorded transactions are less than 90%
                    // of the month difference, then the forecast would not be reliable.
                    if (observations.Count < ((monthDifference / 100) * 90))
                    {
                        return(false);
                    }

                    return(true);
                }
Esempio n. 25
0
        private List <int> ContainsEnoughData(List <int> selectedIds)
        {
            List <int> eligibleIds = new List <int>();

            DateTime today = DateTime.Today;

            foreach (int id in selectedIds)
            {
                Brand  selectedBrand = Hardware.FirstOrDefault(x => x.ConfigId == id).Brand;
                string selectedModel = Hardware.FirstOrDefault(x => x.ConfigId == id).Model;

                DateTime?latestTransactionDate = null;

                try
                {
                    latestTransactionDate = Transactions.Where(x => x.Brand == selectedBrand && x.Model == selectedModel).Max(x => x.Date);
                }
                catch (InvalidOperationException e)
                {
                    Errors.Add($"{selectedBrand} {selectedModel} - No data available.");
                    Errors = Errors.Distinct().ToList();
                    break;
                }

                var datetime        = DateTimeSpan.CompareDates(latestTransactionDate.Value, today);
                int monthDifference = datetime.Years * 12 + datetime.Months;

                System.Diagnostics.Debug.WriteLine($"INSIDE CONTAINS ID:\n    Brand {selectedBrand} Model {selectedModel}\n    Today: {today} Latest Date {latestTransactionDate}\n    Month Difference {monthDifference}");

                if (latestTransactionDate != null && monthDifference <= ALLOWED_TRANSACTION_GAP_MONTHS)
                {
                    eligibleIds.Add(id);
                }
                else
                {
                    Errors.Add($"{selectedBrand} {selectedModel} - {monthDifference} months of data is missing.");
                    Errors = Errors.Distinct().ToList();
                    break;
                }
            }

            return(eligibleIds);
        }
        private string GetApplicationPostedDate(DateTime dt)
        {
            CMSTranslateExtension trans = new CMSTranslateExtension();

            string retDate = trans.GetProviderValueString("talentsearchlblposted");

            DateTime current  = DateTime.Now;
            var      dateSpan = DateTimeSpan.CompareDates(dt, current);

            if (dateSpan.Months < 1)
            {
                retDate += $" {((int)dateSpan.Days / 7).ToString()} {trans.GetProviderValueString("talentsearchlblweeks")} {trans.GetProviderValueString("talentsearchlblpostedago")}";
            }
            else
            {
                // weeks
                retDate += $" {dateSpan.Months.ToString()} {trans.GetProviderValueString("talentsearchlblmonths")} {trans.GetProviderValueString("talentsearchlblpostedago")}";
            }

            return(retDate);
        }
Esempio n. 27
0
        protected override void Execute(CodeActivityContext context)
        {
            DateTime DT1 = Date1DT.Get(context);
            DateTime DT2 = Date2DT.Get(context);

            Dictionary <String, Int32> dict = new Dictionary <string, int>();

            if (DT1 == DateTime.MinValue && DT2 == DateTime.MinValue)
            {
                throw new ArgumentNullException("Input dates", "Input dates are null or have Minimum values.");
            }
            DateTimeSpan dateSpan = DateTimeSpan.CompareDates(DT1, DT2);

            dict["Years"]        = dateSpan.Years;
            dict["Months"]       = dateSpan.Months;
            dict["Days"]         = dateSpan.Days;
            dict["Hours"]        = dateSpan.Hours;
            dict["Minutes"]      = dateSpan.Minutes;
            dict["Seconds"]      = dateSpan.Seconds;
            dict["Milliseconds"] = dateSpan.Milliseconds;

            Difference.Set(context, dict);
        }
Esempio n. 28
0
        private void RemoveUnforecastable(ref List <int> ids, ref List <string> errors)
        {
            List <int> sentIds = ids;

            foreach (int id in sentIds.ToList())
            {
                if (!m_hardwareContext.HardwareConfigurations.Any(x => x.ConfigId == id))
                {
                    ids.Remove(id);
                    errors.Add($"No hardware could be found for id {id}.");
                    continue;
                }

                Hardware hardware = m_hardwareContext.HardwareConfigurations.Where(x => x.ConfigId == id).First();

                if (m_transactionContext.Transactions.Where(x => x.Phone == hardware.PhoneModel).Count() < 24)
                {
                    ids.Remove(id);
                    errors.Add($"{hardware.PhoneModel.GetDisplayName()} - Not enough transactions on record.");
                    continue;
                }

                List <Transaction> allTransactions = m_transactionContext.Transactions.Where(x => x.Phone == hardware.PhoneModel).ToList();
                DateTime           earliestDate    = allTransactions.Min(x => x.PurchaseDate);
                DateTime           latestDate      = allTransactions.Max(x => x.PurchaseDate);
                DateTimeSpan       dateTimeSpan    = DateTimeSpan.CompareDates(earliestDate, latestDate);
                int?monthDifference = (dateTimeSpan.Years * 12) + dateTimeSpan.Days;

                if (monthDifference == null || monthDifference < 24)
                {
                    ids.Remove(id);
                    errors.Add($"{hardware.PhoneModel.GetDisplayName()} - Month difference between the first and last date is not large enough.");
                    continue;
                }
            }
        }
        public MooreForecasting(Component component, List <Hardware> hardware, int months = 12)
        {
            Hardware     earliest     = hardware.OrderBy(x => x.ReleaseDate).First();
            DateTime     startDate    = earliest.ReleaseDate;
            DateTime     endDate      = DateTime.Today.AddMonths(months);
            DateTimeSpan dateTimeSpan = DateTimeSpan.CompareDates(startDate, endDate);
            int          difference   = (dateTimeSpan.Years * 12) + dateTimeSpan.Months;

            System.Diagnostics.Debug.WriteLine($"MOORE DIFFERENCE {startDate} {endDate} - {difference}");

            double startValue;

            if (component == Component.CPUSpeed)
            {
                startValue = earliest.ProcessorCoreSpeed * earliest.ProcessorCoreCount;
            }
            else if (component == Component.InternalStorageSpace)
            {
                startValue = earliest.InternalStorageSpace;
            }
            else if (component == Component.RAM)
            {
                startValue = earliest.RAM;
            }
            else if (component == Component.FrontCameraMegapixel)
            {
                startValue = earliest.FrontCameraMegapixel;
            }
            else if (component == Component.RearCameraMegapixel)
            {
                startValue = earliest.RearCameraMegapixel;
            }
            else if (component == Component.MaxFramerateMaxResolution)
            {
                startValue = earliest.MaxFramerateMaxResolution;
            }
            else if (component == Component.MaxFramerateMinResolution)
            {
                startValue = earliest.MaxFramerateMinResolution;
            }
            else if (component == Component.BatteryCapacity)
            {
                startValue = earliest.BatteryCapacity;
            }
            else if (component == Component.Volume)
            {
                startValue = (earliest.Height * earliest.Depth * earliest.Width);
            }
            else if (component == Component.Price)
            {
                startValue = earliest.OriginalPrice;
            }
            else
            {
                startValue = 1;
            }

            m_ForecastResults.Add(new ForecastResult(startDate, startValue));

            for (int i = 0; i < difference; i++)
            {
                m_ForecastResults.Add(new ForecastResult(m_ForecastResults[m_ForecastResults.Count - 1].Date.AddMonths(1), (startValue * Math.Pow(1.029303, i))));
            }
        }
Esempio n. 30
0
        public double IntrestCalculator(String AccName, string DealNo, DateTime CDt)
        {
            DataTable dtf  = new DataTable();
            funs11    fObj = new funs11();

            Database.GetSqlData("SELECT journal.Vdate, journal.Narr, journal.Dr, journal.Cr, VOUCHERINFO.dealno FROM journal INNER JOIN VOUCHERINFO ON journal.Vi_id = VOUCHERINFO.Vi_id WHERE (journal.[Vi_id]=" + DealNo + " or dealno=" + DealNo + " )AND journal.[Ac_id]=" + funs11.Select_ac_id(AccName) + " and journal.Vdate<= #" + CDt.ToString("dd-MMM-yyyy") + "# ORDER BY journal.Vdate", dtf);

            dtf.Columns.Add("Balance", typeof(double));
            dtf.Columns.Add("Days", typeof(int));
            dtf.Columns.Add("Wbal", typeof(double));

            dtf.Rows.Add(CDt.ToString("dd-MMM-yyyy"), "", 0, 0, 0, 0, 0);
            double rbalance = 0;

            for (int i = 0; i < dtf.Rows.Count; i++)
            {
                if (double.Parse(dtf.Rows[i]["Dr"].ToString()) > double.Parse(dtf.Rows[i]["Cr"].ToString()))
                {
                    rbalance = rbalance + double.Parse(dtf.Rows[i]["Dr"].ToString());
                    dtf.Rows[i]["Balance"] = rbalance;
                }
                else if (double.Parse(dtf.Rows[i]["Cr"].ToString()) > double.Parse(dtf.Rows[i]["Dr"].ToString()))
                {
                    rbalance = rbalance - double.Parse(dtf.Rows[i]["Cr"].ToString());
                    dtf.Rows[i]["Balance"] = rbalance;
                }
                else
                {
                    dtf.Rows[i]["Balance"] = rbalance;
                }

                if (i < dtf.Rows.Count - 1)
                {
                    dtf.Rows[i]["Days"] = ((DateTime)dtf.Rows[i + 1]["Vdate"] - (DateTime)dtf.Rows[i]["Vdate"]).Days.ToString();
                }
                else
                {
                    dtf.Rows[i]["Days"] = "0";
                }
                dtf.Rows[i]["Wbal"] = double.Parse(dtf.Rows[i]["Balance"].ToString()) * double.Parse(dtf.Rows[i]["Days"].ToString());
            }

            int    tdays = int.Parse(dtf.Compute("Sum(Days)", "").ToString());
            double twbal = int.Parse(dtf.Compute("Sum(Wbal)", "").ToString());
            double abalance;

            if (tdays == 0)
            {
                abalance = 0;
            }
            else
            {
                abalance = twbal / tdays;
            }
            double irate = 0;

            irate = Database.GetScalarDecimal("select int_rate from voucherinfo where Vi_id=" + DealNo);



            var dateSpan = DateTimeSpan.CompareDates((DateTime)dtf.Compute("max(Vdate)", ""), (DateTime)dtf.Compute("min(Vdate)", ""));

            double Months = ((dateSpan.Years * 12) + dateSpan.Months + (double.Parse(dateSpan.Days.ToString()) / 30));

            double interest = abalance * irate * Months / 100;


            //dataGridView1.DataSource = dtf;
            //dataGridView1.Columns["Vdate"].Width = 100;
            //dataGridView1.Columns["Narr"].Width = 100;
            //dataGridView1.Columns["Dr"].Width = 100;
            //dataGridView1.Columns["Cr"].Width = 100;
            //dataGridView1.Columns["Narr"].HeaderText = "Particular";
            //dataGridView1.Columns["Vdate"].DisplayIndex = 0;
            //dataGridView1.Columns["Narr"].DisplayIndex = 1;
            //dataGridView1.Columns["Dr"].DisplayIndex = 2;
            //dataGridView1.Columns["Cr"].DisplayIndex = 3;
            if (double.Parse(funs11.DecimalPoint(interest.ToString())) < 0)
            {
                return(-1 * double.Parse(funs11.DecimalPoint(interest.ToString())));
            }
            else
            {
                return(double.Parse(interest.ToString()));
            }
        }