Example #1
0
        public static void Run()
        {
            // Create a workbook
            Workbook wb = new Workbook();

            // Accesss first worksheet
            Worksheet ws = wb.Worksheets[0];

            // Add some text in cell A1
            ws.Cells["A1"].PutValue("Welcome to ");

            // Create a calculation options with custom engine
            CalculationOptions opts = new CalculationOptions();

            opts.CustomEngine = new ICustomEngine();

            // This line shows how you can call your own custom function without
            // a need to write it in any worksheet cell
            // After the execution of this line, it will return
            // Welcome to Aspose.Cells.
            object ret = ws.CalculateFormula("=A1 & MyCompany.CustomFunction()", opts);

            // Print the calculated value on Console
            Console.WriteLine("Calculated Value: " + ret);
        }
        // ExStart:TestCalcTimeRecursive
        static void TestCalcTimeRecursive(bool rec)
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            // Load your sample workbook
            Workbook wb = new Workbook(dataDir + "sample.xlsx");

            // Access first worksheet
            Worksheet ws = wb.Worksheets[0];

            // Set the calculation option, set recursive true or false as per parameter
            CalculationOptions opts = new CalculationOptions();
            opts.Recursive = rec;

            // Start stop watch            
            Stopwatch sw = new Stopwatch();
            sw.Start();

            // Calculate cell A1 one million times
            for (int i = 0; i < 1000000; i++)
            {
                ws.Cells["A1"].Calculate(opts);
            }

            // Stop the watch
            sw.Stop();

            // Calculate elapsed time in seconds
            long second = 1000;
            long estimatedTime = sw.ElapsedMilliseconds / second;

            // Print the elapsed time in seconds
            Console.WriteLine("Recursive " + rec + ": " + estimatedTime + " seconds");

        }
 public static double CalculateAverageConsumption(int itemId,int storeId, DateTime startDate, DateTime endDate, CalculationOptions option)
 {
     var numberOfDays = endDate.Subtract(startDate).TotalDays;
     var totalCosumption = CalculateTotalConsumption(itemId,storeId, startDate, endDate) * 1.0;
     switch (option)
     {
         case CalculationOptions.Daily:
             return totalCosumption / numberOfDays;
             break;
         case CalculationOptions.Weekly:
             return totalCosumption / (numberOfDays / 7);
             break;
         case CalculationOptions.Monthly:
             return totalCosumption / (numberOfDays / 30);
             break;
         case CalculationOptions.Quarterly:
             return totalCosumption / (numberOfDays / 123);
             break;
         case CalculationOptions.Annual:
             return totalCosumption / (numberOfDays / 365);
             break;
         default:
             break;
     }
     return 0;
 }
Example #4
0
        static int RunWithOptions(CalculationOptions calculationOptions)
        {
            Console.WriteLine("========================");
            Console.WriteLine($"EnableThreadingAfterXCharacters: {calculationOptions.EnableThreadingAfterXCharacters}");
            Console.WriteLine($"MinimumCharactersPerThread: {calculationOptions.MinimumCharactersPerThread}");
            Console.WriteLine("========================");

            var numberOfFailures = 0;

            for (var i = 0; i < NUMBER_OF_CHECKS; i++)
            {
                var source = WordGenerator.GenerateWord(WORD_LENGTH);
                var target = WordGenerator.GenerateWord(WORD_LENGTH);

                var baseline      = Benchmarks.LevenshteinBaseline.GetDistance(source, target);
                var quickenshtein = Levenshtein.GetDistance(source, target);

                if (baseline != quickenshtein)
                {
                    Console.WriteLine($"FAILED ({i + 1}): Expected {baseline}, Actual {quickenshtein}");
                    Console.WriteLine($"Source: {source}");
                    Console.WriteLine($"Target: {target}");
                    numberOfFailures++;
                }
            }

            Console.WriteLine("========================");
            Console.WriteLine($"Number of Failures: {numberOfFailures}");
            Console.WriteLine("========================");
            Console.WriteLine();

            return(numberOfFailures);
        }
        public static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            // Create workbook
            Workbook wb = new Workbook();
            Cells cells = wb.Worksheets[0].Cells;

            // Set formula
            Cell cell = cells[0, 0];
            cell.SetArrayFormula("=MYFUNC()", 2, 2);

            Style style = cell.GetStyle();
            style.Number = 14;
            cell.SetStyle(style);

            // Set calculation options for formula
            CalculationOptions copt = new CalculationOptions();
            copt.CustomFunction = new CustomFunctionStaticValue();
            wb.CalculateFormula(copt);

            // Save to xlsx by setting the calc mode to manual
            wb.Settings.CalcMode = CalcModeType.Manual;
            wb.Save(dataDir + "output_out.xlsx");

            // Save to pdf
            wb.Save(dataDir + "output_out.pdf");
            // ExEnd:1
        }
        public static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            // Create workbook
            Workbook workbook = new Workbook();
            Cells    cells    = workbook.Worksheets[0].Cells;

            // Set formula
            Cell cell = cells[0, 0];

            cell.SetArrayFormula("=MYFUNC()", 2, 2);

            Style style = cell.GetStyle();

            style.Number = 14;
            cell.SetStyle(style);

            // Set calculation options for formula
            CalculationOptions calculationOptions = new CalculationOptions();

            calculationOptions.CustomEngine = new CustomFunctionStaticValue();
            workbook.CalculateFormula(calculationOptions);

            // Save to xlsx by setting the calc mode to manual
            workbook.Settings.CalcMode = CalcModeType.Manual;
            workbook.Save(dataDir + "output_out.xlsx");

            // Save to pdf
            workbook.Save(dataDir + "output_out.pdf");
            // ExEnd:1
        }
 public ThreadedLevenshteinTests()
 {
     CalculationOptions = new CalculationOptions
     {
         EnableThreadingAfterXCharacters = 0,
         MinimumCharactersPerThread      = 16
     };
 }
        private async Task AddWealthInformationAsync(DateTime previousMonth, MonthlyDigestData digestData, int appOwnerId)
        {
            Sheet sheet = await this._sheetRetrievalService.GetBySubjectAsync(previousMonth.Month, previousMonth.Year, appOwnerId);

            CalculationOptions calcOffset = this._calculationService.CalculateOffset(sheet);

            digestData.Wealth.BankAccount.PreviousAmount = calcOffset.BankAccountOffset ?? 0;
            digestData.Wealth.BankAccount.Amount         = digestData.Wealth.BankAccount.PreviousAmount + CalculateFigure(sheet, se => se.Account == AccountType.BankAccount);

            digestData.Wealth.SavingsAccount.PreviousAmount = calcOffset.SavingsAccountOffset ?? 0;
            digestData.Wealth.SavingsAccount.Amount         = digestData.Wealth.SavingsAccount.PreviousAmount + CalculateFigure(sheet, se => se.Account == AccountType.SavingsAccount);
        }
Example #9
0
        public void CellsWorkbookPostWorkbookCalculateFormulaTest()
        {
            string             name    = "Book1.xlsx";
            CalculationOptions options = new CalculationOptions();

            options.IgnoreError = true;
            bool?  ignoreError = true;
            string folder      = null;

            new Config().UpdateDataFile(folder, name);
            var response = instance.CellsWorkbookPostWorkbookCalculateFormula(name, options, ignoreError, folder);

            Console.WriteLine(response);
        }
        /// <summary>
        /// Calculates the offset of the sheet based on previous sheets
        /// </summary>
        /// <returns></returns>
        public CalculationOptions CalculateOffset(Sheet targetSheet)
        {
            int ownerId = targetSheet.Owner.Id;

            // TODO: When Entity Framework properly supports 'select many from many', revert this query
            var q = (from entry in this._sheetRepository.GetOfSheetBeforeThreshold(ownerId, targetSheet.Subject)
                     select new { entry.Account, entry.Delta }).ToArray();

            var result = new CalculationOptions()
            {
                BankAccountOffset    = targetSheet.CalculationOptions.BankAccountOffset ?? q.Where(x => x.Account == AccountType.BankAccount).Sum(x => (decimal?)x.Delta).GetValueOrDefault(0),
                SavingsAccountOffset = targetSheet.CalculationOptions.SavingsAccountOffset ?? q.Where(x => x.Account == AccountType.SavingsAccount).Sum(x => (decimal?)x.Delta).GetValueOrDefault(0)
            };

            return(result);
        }
        /// <summary>
        /// Calculates the offset of the sheet based on previous sheets
        /// </summary>
        /// <returns></returns>
        public CalculationOptions CalculateOffset(Sheet targetSheet)
        {
            int ownerId = targetSheet.Owner.Id;

            var q = (from Sheet s in this._sheetRepository.GetByOwner(ownerId)
                    where s.Subject < targetSheet.Subject
                    from SheetEntry entry in s.Entries
                    select new {entry.Account, entry.Delta}).ToArray();

            var result = new CalculationOptions() {
                BankAccountOffset = targetSheet.CalculationOptions.BankAccountOffset ?? q.Where(x => x.Account == AccountType.BankAccount).Sum(x=>(decimal?)x.Delta).GetValueOrDefault(0),
                SavingsAccountOffset = targetSheet.CalculationOptions.SavingsAccountOffset ?? q.Where(x => x.Account == AccountType.SavingsAccount).Sum(x=>(decimal?)x.Delta).GetValueOrDefault(0)
            };

            return result;
        }
        public void CellsPostCellCalculateExample()
        {
            string             name      = "Book1.xlsx";
            string             sheetName = "SHEET1";
            string             cellName  = "A1";
            CalculationOptions options   = new CalculationOptions();

            options.Recursive   = true;
            options.IgnoreError = true;
            string folder = null;

            new Config().UpdateDataFile(null, "Book1.xlsx");
            var response = instance.CellsPostCellCalculate(name, sheetName, cellName, options, folder);

            Console.WriteLine(response);
        }
        public void CellsWorkbookPostWorkbookCalculateFormulaTest()
        {
            // TODO uncomment below to test the method and replace null with proper value
            string             name    = BOOK1;
            CalculationOptions options = new CalculationOptions();

            options.IgnoreError = true;
            bool?  ignoreError = true;
            string folder      = TEMPFOLDER;

            UpdateDataFile(instance, folder, name);
            var response = instance.CellsWorkbookPostWorkbookCalculateFormula(name, options, ignoreError, folder);

            Assert.IsInstanceOf <CellsCloudResponse>(response, "response is CellsCloudResponse");
            Assert.AreEqual(response.Code, 200);
        }
        /// <summary>
        /// Calculates the offset of the sheet based on previous sheets
        /// </summary>
        /// <returns></returns>
        public CalculationOptions CalculateOffset(Sheet targetSheet)
        {
            int ownerId = targetSheet.Owner.Id;

            var q = (from Sheet s in this._sheetRepository.GetByOwner(ownerId)
                     where s.Subject < targetSheet.Subject
                     from SheetEntry entry in s.Entries
                     select new { entry.Account, entry.Delta }).ToArray();

            var result = new CalculationOptions()
            {
                BankAccountOffset    = targetSheet.CalculationOptions.BankAccountOffset ?? q.Where(x => x.Account == AccountType.BankAccount).Sum(x => (decimal?)x.Delta).GetValueOrDefault(0),
                SavingsAccountOffset = targetSheet.CalculationOptions.SavingsAccountOffset ?? q.Where(x => x.Account == AccountType.SavingsAccount).Sum(x => (decimal?)x.Delta).GetValueOrDefault(0)
            };

            return(result);
        }
        public static void Main()
        {
            // ExStart:1
            LoadOptions LoadOptions = new LoadOptions();
            var         objWB       = new Aspose.Cells.Workbook(sourceDir + "Circular Formulas.xls", LoadOptions);

            objWB.Settings.Iteration = true;
            CalculationOptions copts = new CalculationOptions();
            CircularMonitor    cm    = new CircularMonitor();

            copts.CalculationMonitor = cm;
            objWB.CalculateFormula(copts);
            long lngCircularRef = cm.circulars.Count;

            Console.WriteLine("Circular References found - " + lngCircularRef);
            // ExEnd:1
            Console.WriteLine("DetectCircularReference executed successfully.\r\n");
        }
        public void CellsPostCellCalculateTest()
        {
            // TODO uncomment below to test the method and replace null with proper value
            string             name      = BOOK1;
            string             sheetName = SHEET1;
            string             cellName  = CellName;
            CalculationOptions options   = new CalculationOptions();

            options.Recursive   = true;
            options.IgnoreError = true;
            string folder = TEMPFOLDER;

            UpdateDataFile(TEMPFOLDER, BOOK1);
            var response = instance.CellsPostCellCalculate(name, sheetName, cellName, options, folder);

            Assert.IsInstanceOf <SaaSposeResponse>(response, "response is SaaSposeResponse");
            Assert.AreEqual(response.Status, "OK");
        }
        }         //clsCalculationMonitor

        public static void Run()
        {
            //Source directory
            string sourceDir = RunExamples.Get_SourceDirectory();

            //Load the sample Excel file
            Workbook wb = new Workbook(sourceDir + "sampleCalculationMonitor.xlsx");

            //Create calculation options and assign instance of calculation monitor class
            CalculationOptions opts = new CalculationOptions();

            opts.CalculationMonitor = new clsCalculationMonitor();

            //Calculate formula with calculation options
            wb.CalculateFormula(opts);

            Console.WriteLine("InterruptOrCancelFormulaCalculationOfWorkbook executed successfully.\r\n");
        }
Example #18
0
        public static void Main(string[] args)
        {
            // Create an instance of Workbook
            Workbook workbook = new Workbook();

            // Access first Worksheet from the collection
            Worksheet sheet = workbook.Worksheets[0];

            // Access Cell A1 and put a formula to sum values of B1 to B2
            Cell a1 = sheet.Cells["A1"];

            a1.Formula = "=Sum(B1:B2)";

            // Assign values to cells B1 & B2
            sheet.Cells["B1"].PutValue(10);
            sheet.Cells["B2"].PutValue(10);

            // Calculate all formulas in the Workbook
            workbook.CalculateFormula();

            // The result of A1 should be 20 as per default calculation engine
            Console.WriteLine("The value of A1 with default calculation engine: " + a1.StringValue);

            // Create an instance of CustomEngine
            CustomEngine engine = new CustomEngine();

            // Create an instance of CalculationOptions
            CalculationOptions opts = new CalculationOptions();

            // Assign the CalculationOptions.CustomEngine property to the instance of CustomEngine
            opts.CustomEngine = engine;

            // Recalculate all formulas in Workbook using the custom calculation engine
            workbook.CalculateFormula(opts);

            // The result of A1 will be 50 as per custom calculation engine
            Console.WriteLine("The value of A1 with custom calculation engine: " + a1.StringValue);

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
        public static void Run()
        {
            // Create an instance of Workbook
            Workbook workbook = new Workbook();

            // Access first Worksheet from the collection
            Worksheet sheet = workbook.Worksheets[0];

            // Access Cell A1 and put a formula to sum values of B1 to B2
            Cell a1 = sheet.Cells["A1"];
            a1.Formula = "=Sum(B1:B2)";

            // Assign values to cells B1 & B2
            sheet.Cells["B1"].PutValue(10);
            sheet.Cells["B2"].PutValue(10);

            // Calculate all formulas in the Workbook 
            workbook.CalculateFormula();

            // The result of A1 should be 20 as per default calculation engine
            Console.WriteLine("The value of A1 with default calculation engine: " + a1.StringValue);

            // Create an instance of CustomEngine
            CustomEngine engine = new CustomEngine();

            // Create an instance of CalculationOptions
            CalculationOptions opts = new CalculationOptions();

            // Assign the CalculationOptions.CustomEngine property to the instance of CustomEngine
            opts.CustomEngine = engine;

            // Recalculate all formulas in Workbook using the custom calculation engine
            workbook.CalculateFormula(opts);

            // The result of A1 will be 50 as per custom calculation engine
            Console.WriteLine("The value of A1 with custom calculation engine: " + a1.StringValue);

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Example #20
0
        //aspose
        private void button3_Click(object sender, EventArgs e)
        {
            Workbook workbook = new Workbook(@"2year.xlsx");

            Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0];
            Cell cell = worksheet.Cells[2, 0];

            cell.PutValue(40000);

            var options = new CalculationOptions();

            options.IgnoreError = true;
            worksheet.CalculateFormula(options, true);
            workbook.Save(@"test2.xlsx", Aspose.Cells.SaveFormat.Xlsx);

            Workbook workbook2 = new Workbook(@"2year.xlsx");

            Aspose.Cells.Worksheet worksheet2 = workbook2.Worksheets[0];
            Cell cell2 = worksheet2.Cells[2, 2];

            MessageBox.Show(cell2.Value.ToString());
        }
        public override Bitmap DrawBitmap(OrbitMap m, RenderOptions rp, CalculationOptions co, Constraints[] orbitConstraints)
        {
            Bitmap b = new Bitmap(rp.CanvasWidth, rp.CanvasHeight, PixelFormat.Format32bppRgb);
            BitmapData bd = b.LockBits(new Rectangle(0, 0, rp.CanvasWidth, rp.CanvasHeight), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);

            uint maxIter = m.Max(o => o.Iterations);

            foreach (Orbit o in m)
            {
                if (o.X >= 0 && o.X < b.Width &&
                    o.Y >= 0 && o.Y < b.Height)
                {
                    uint gray = ColorFunc(o.Iterations, co.IterationCount);

                    Marshal.WriteInt32(bd.Scan0 + o.Y * bd.Stride + o.X * 4,
                                       unchecked((int)((gray << 24) | (gray << 16) | (gray << 8) | gray)));
                }
            }

            b.UnlockBits(bd);
            return b;
        }
        public unsafe override Bitmap DrawBitmap(OrbitMap m, RenderOptions rp, CalculationOptions co, Constraints[] orbitConstraints)
        {
            Bitmap b = new Bitmap(rp.CanvasWidth, rp.CanvasHeight, PixelFormat.Format32bppRgb);
            BitmapData bd = b.LockBits(new Rectangle(0, 0, rp.CanvasWidth, rp.CanvasHeight), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);

            uint maxIter = m.Max(o => o.Iterations);

            uint* pixels = (uint*)bd.Scan0.ToPointer();
            foreach (Orbit o in m)
            {
                if (o.X >= 0 && o.X < b.Width &&
                    o.Y >= 0 && o.Y < b.Height)
                {
                    uint gray = ColorFunc(o.Iterations, co.IterationCount);

                    pixels[o.Y * bd.Stride / 4 + o.X] = (gray << 24) | (gray << 16) | (gray << 8) | gray;
                }
            }

            b.UnlockBits(bd);
            return b;
        }
        public static void Run()
        {
            // ExStart:UsingAbstractCalculationEnginefeature
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            // Open the workbook
            Workbook workbook = new Workbook();

            // Obtaining the reference of the first worksheet
            Worksheet worksheet = workbook.Worksheets[0];

            // Adding sample values to cells
            worksheet.Cells["B1"].PutValue(5);
            worksheet.Cells["C1"].PutValue(100);
            worksheet.Cells["C2"].PutValue(150);
            worksheet.Cells["C3"].PutValue(60);
            worksheet.Cells["C4"].PutValue(32);
            worksheet.Cells["C5"].PutValue(62);

            // Adding custom formula to Cell A1
            workbook.Worksheets[0].Cells["A1"].Formula = "=MyFunc(B1,C1:C5)";

            // Set calculation options
            CalculationOptions calculationOptions = new CalculationOptions();

            calculationOptions.CustomEngine = new CustomFunction();

            // Calcualting Formulas
            workbook.CalculateFormula(calculationOptions);

            // Assign resultant value to Cell A1
            workbook.Worksheets[0].Cells["A1"].PutValue(workbook.Worksheets[0].Cells["A1"].Value);

            // Save the file
            workbook.Save(dataDir + "UsingAbstractCalculationEnginefeature_out.xls");
            // ExEnd:UsingAbstractCalculationEnginefeature
        }
    public void ChangeCalculationInterval(float value)
    {
        float newTime = 0.0f;

        CalculationOptions choice = (CalculationOptions)Mathf.RoundToInt(value);

        switch (choice)
        {
        case CalculationOptions.time5secs:
            newTime = 5.0f;
            break;

        case CalculationOptions.time10secs:
            newTime = 10.0f;
            break;

        case CalculationOptions.time15secs:
            newTime = 15.0f;
            break;

        case CalculationOptions.time20secs:
            newTime = 20.0f;
            break;

        default:
            Debug.LogError("Invalid calculation interval");
            break;
        }
        Debug.Log("ChangeBaseline: " + newTime);

        // Store data to apply changes
        tempCalculationInterval  = newTime;
        calculationIntervChanged = true;

        // Notify changes in UI
        ChangesInUIWereDone();
    }
        // ExStart:TestCalcTimeRecursive
        static void TestCalcTimeRecursive(bool rec)
        {
            //Source directory
            string sourceDir = RunExamples.Get_SourceDirectory();

            // Load your sample workbook
            Workbook wb = new Workbook(sourceDir + "sampleDecreaseCalculationTime.xlsx");

            // Access first worksheet
            Worksheet ws = wb.Worksheets[0];

            // Set the calculation option, set recursive true or false as per parameter
            CalculationOptions opts = new CalculationOptions();

            opts.Recursive = rec;

            // Start stop watch
            Stopwatch sw = new Stopwatch();

            sw.Start();

            // Calculate cell A1 one million times
            for (int i = 0; i < 1000000; i++)
            {
                ws.Cells["A1"].Calculate(opts);
            }

            // Stop the watch
            sw.Stop();

            // Calculate elapsed time in seconds
            long second        = 1000;
            long estimatedTime = sw.ElapsedMilliseconds / second;

            // Print the elapsed time in seconds
            Console.WriteLine("Recursive " + rec + ": " + estimatedTime + " seconds");
        }
        // ExStart:TestCalcTimeRecursive
        static void TestCalcTimeRecursive(bool rec)
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            // Load your sample workbook
            Workbook wb = new Workbook(dataDir + "sample.xlsx");

            // Access first worksheet
            Worksheet ws = wb.Worksheets[0];

            // Set the calculation option, set recursive true or false as per parameter
            CalculationOptions opts = new CalculationOptions();

            opts.Recursive = rec;

            // Start stop watch
            Stopwatch sw = new Stopwatch();

            sw.Start();

            // Calculate cell A1 one million times
            for (int i = 0; i < 1000000; i++)
            {
                ws.Cells["A1"].Calculate(opts);
            }

            // Stop the watch
            sw.Stop();

            // Calculate elapsed time in seconds
            long second        = 1000;
            long estimatedTime = sw.ElapsedMilliseconds / second;

            // Print the elapsed time in seconds
            Console.WriteLine("Recursive " + rec + ": " + estimatedTime + " seconds");
        }
        public static void Run()
        {
            // Create a workbook
            Workbook wb = new Workbook();

            // Accesss first worksheet
            Worksheet ws = wb.Worksheets[0];

            // Add some text in cell A1
            ws.Cells["A1"].PutValue("Welcome to ");

            // Create a calculation options with custom engine
            CalculationOptions opts = new CalculationOptions();
            opts.CustomEngine = new ICustomEngine();

            // This line shows how you can call your own custom function without
            // a need to write it in any worksheet cell
            // After the execution of this line, it will return
            // Welcome to Aspose.Cells.
            object ret = ws.CalculateFormula("=A1 & MyCompany.CustomFunction()", opts);

            // Print the calculated value on Console
            Console.WriteLine("Calculated Value: " + ret);
        }
Example #28
0
 public abstract Bitmap DrawBitmap(OrbitMap m, RenderOptions rp, CalculationOptions co, Constraints[] orbitConstraints);
Example #29
0
        private static string ParseAsBinding(string expressionString, Expression functionExpressionParm, CalculationOptions calculationOptions, Token binaryExpressionToken = null)
        {
            if (functionExpressionParm is BindingExpression bindingExpression)
            {
                return(FormatAsType(bindingExpression.Value) ?? bindingExpression._expression);
            }

            return(null);
        }
Example #30
0
        private static string ParseAsVariable(string expressionString, Expression functionExpressionParm, CalculationOptions calculationOptions, Token binaryExpressionToken = null)
        {
            if (functionExpressionParm is VariableExpression variableExpression)
            {
                return(FormatAsType(variableExpression.Value) ?? variableExpression._name);
            }

            if (functionExpressionParm.GetType() == typeof(Expression))
            {
                var tokenValue = functionExpressionParm._token.Value;
                if (!(tokenValue is string) && tokenValue is IEnumerable enumerable)
                {
                    return("[" + string.Join(", ", enumerable.Cast <object>().Select(FormatAsType)) + "]");
                }

                return(FormatAsType(tokenValue));
            }

            return(null);
        }
Example #31
0
        private static string ParseAsBinary(string expressionString, Expression expression, CalculationOptions calculationOptions)
        {
            if (expression is BinaryExpression binaryExpression)
            {
                List <string> list = new List <string>();

                var expressionString1 = ParseAsBinding(expressionString, binaryExpression._lft, calculationOptions);
                list.Add(expressionString1);
                var expressionString2 = ParseAsBinding(expressionString, binaryExpression._rgt, calculationOptions, binaryExpression._token);
                list.Add(expressionString2);
                var expressionString3 = ParseAsVariable(expressionString, binaryExpression._lft, calculationOptions);
                list.Add(expressionString3);
                var expressionString4 = ParseAsVariable(expressionString, binaryExpression._rgt, calculationOptions, binaryExpression._token);
                list.Add(expressionString4);
                var expressionString5 = ParseAsBinary(expressionString, binaryExpression._lft, calculationOptions);
                list.Add(expressionString5);
                var expressionString6 = ParseAsBinary(expressionString, binaryExpression._rgt, calculationOptions);
                list.Add(expressionString6);
                var expressionString7 = ParseAsFunction(expressionString, binaryExpression._lft, calculationOptions);
                list.Add(expressionString7);
                var expressionString8 = ParseAsFunction(expressionString, binaryExpression._rgt, calculationOptions);
                list.Add(expressionString8);
                return(string.Join(" " + binaryExpression._token.Value + " ", list.Where(s => !string.IsNullOrEmpty(s))));
            }

            return(null);
        }
Example #32
0
        private static string ParseAsFunction(string expressionString, Expression expression, CalculationOptions calculationOptions)
        {
            if (expression is FunctionExpression functionExpression)
            {
                var           methodName = functionExpression._fn.FunctionName;
                List <string> list       = new List <string>();
                foreach (var functionExpressionParam in functionExpression.Parms)
                {
                    list.Add(ParseAsFunction(expressionString, functionExpressionParam, calculationOptions));
                    list.Add(ParseAsBinding(expressionString, functionExpressionParam, calculationOptions));
                    list.Add(ParseAsVariable(expressionString, functionExpressionParam, calculationOptions));
                }
                return(methodName + "(" + string.Join(", ", list.Where(s => !string.IsNullOrEmpty(s))) + ")" + GetResult(functionExpression.Value));
            }

            return(null);
        }
Example #33
0
        internal static string ParseBindings(Expression expression, string expressionString, CalculationOptions calculationOptions, object result)
        {
            List <string> list = new List <string>
            {
                ParseAsFunction(expressionString, expression, calculationOptions),
                ParseAsBinding(expressionString, expression, calculationOptions),
                ParseAsVariable(expressionString, expression, calculationOptions),
                ParseAsBinary(expressionString, expression, calculationOptions)
            };

            var replace = string.Join(", ", list.Where(s => !string.IsNullOrEmpty(s))).Replace("**", "*");
            var value   = GetResult(result);

            if (!replace.EndsWith(value))
            {
                replace = "(" + replace + ")" + value;
            }

            return(replace);
        }
Example #34
0
 public void Add(CalculationOptions calculationOptions)
 {
     this._dbContext.Set <CalculationOptions>().Add(calculationOptions);
 }
Example #35
0
        private void buttonCalculate_Click(object sender, EventArgs e)
        {
            _MagCalculator = null;
            saveToolStripMenuItem.Enabled = false;

            this.errorProviderCheck.SetError(comboBoxModels, string.Empty);
            this.errorProviderCheck.SetError(comboBoxAltitudeUnits, string.Empty);
            this.errorProviderCheck.SetError(textBoxAltitude, string.Empty);
            this.errorProviderCheck.SetError(textBoxLatitudeDecimal, string.Empty);
            this.errorProviderCheck.SetError(textBoxLongitudeDecimal, string.Empty);

            if (comboBoxModels.SelectedValue == null)
            {
                this.errorProviderCheck.SetError(comboBoxModels, @"No Model selected");
                return;
            }

            var selectedModel = Models.TList.Find(model => model.ID.Equals(comboBoxModels.SelectedValue));

            if (selectedModel != null)
            {
                //if (DBNull.Value.Equals(dRow.First()["FileName"]))
                //{
                //    this.errorProviderCheck.SetError(comboBoxModels, @"No file name was found for the model you selected");
                //    return;
                //}

                //string modelFile = dRow.First()["FileName"].ToString();

                //if (!File.Exists(modelFile))
                //{
                //    this.errorProviderCheck.SetError(comboBoxModels, string.Format("The model file {0} could not be found", Path.GetFileName(modelFile)));
                //    return;
                //}

                if (comboBoxAltitudeUnits.SelectedItem == null)
                {
                    this.errorProviderCheck.SetError(comboBoxAltitudeUnits, @"No Units have been selected");
                    return;
                }

                if (string.IsNullOrEmpty(textBoxAltitude.Text) || !Helper.IsNumeric(textBoxAltitude.Text))
                {
                    this.errorProviderCheck.SetError(textBoxAltitude, @"Altitude must be a valid number");
                    return;
                }

                double altitude = Convert.ToDouble(textBoxAltitude.Text);

                var altUnit = Distance.FromString(comboBoxAltitudeUnits.SelectedItem.ToString());

                if (string.IsNullOrEmpty(textBoxLatitudeDecimal.Text) || !Helper.IsNumeric(textBoxLatitudeDecimal.Text))
                {
                    this.errorProviderCheck.SetError(textBoxLatitudeDecimal, @"Latitude must be a valid number");
                    return;
                }

                if (string.IsNullOrEmpty(textBoxLongitudeDecimal.Text) || !Helper.IsNumeric(textBoxLongitudeDecimal.Text))
                {
                    this.errorProviderCheck.SetError(textBoxLongitudeDecimal, @"Longitude must be a valid number");
                    return;
                }

                Cursor = Cursors.WaitCursor;

                var calcOptions = new CalculationOptions
                {
                    Latitude     = Convert.ToDouble(textBoxLatitudeDecimal.Text),
                    Longitude    = Convert.ToDouble(textBoxLongitudeDecimal.Text),
                    StartDate    = dateTimePicker1.Value,
                    StepInterval = Convert.ToDouble(numericUpDownStepSize.Value),
                };

                calcOptions.SetElevation(altitude, altUnit, ApplicationPreferences.UseAltitude);

                dataGridViewResults.Rows.Clear();

                try
                {
                    _MagCalculator = new GeoMag();

                    _MagCalculator.LoadModel(selectedModel);

                    if (toolStripMenuItemUseRangeOfDates.Checked)
                    {
                        calcOptions.EndDate = dateTimePicker2.Value;
                    }

                    _MagCalculator.MagneticCalculations(calcOptions);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error: Calculating Magnetics", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    _MagCalculator = null;
                }

                if (_MagCalculator == null)
                {
                    Cursor = Cursors.Default;
                    return;
                }

                if (_MagCalculator.ResultsOfCalculation == null || !_MagCalculator.ResultsOfCalculation.Any())
                {
                    Cursor = Cursors.Default;
                    MessageBox.Show(this, "No Calculations were returned for the given parameters", "No Calculation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                foreach (var mag in _MagCalculator.ResultsOfCalculation)
                {
                    if (mag == null)
                    {
                        continue;
                    }

                    dataGridViewResults.Rows.Add();

                    dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnDate"].Value = mag.Date.ToShortDateString();

                    dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnDeclination"].Value = string.Format("{0}°", (mag.EastComp == null ? double.NaN.ToString() : mag.Declination.Value.ToString("F3")));

                    dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnInclination"].Value = string.Format("{0}°", (mag.EastComp == null ? double.NaN.ToString() : mag.Inclination.Value.ToString("F3")));

                    dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnHorizontalIntensity"].Value = string.Format("{0} nT", (mag.EastComp == null ? double.NaN.ToString() : mag.HorizontalIntensity.Value.ToString("F2")));

                    dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnNorthComp"].Value = string.Format("{0} nT", (mag.EastComp == null ? double.NaN.ToString() : mag.NorthComp.Value.ToString("F2")));

                    dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnEastComp"].Value = string.Format("{0} nT", (mag.EastComp == null ? double.NaN.ToString() : mag.EastComp.Value.ToString("F2")));

                    dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnVerticalComp"].Value = string.Format("{0} nT", (mag.EastComp == null ? double.NaN.ToString() : mag.VerticalComp.Value.ToString("F2")));

                    dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnTotalField"].Value = string.Format("{0} nT", (mag.EastComp == null ? double.NaN.ToString() : mag.TotalField.Value.ToString("F2")));
                }

                dataGridViewResults.Rows.Add();

                dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnDate"].Value           = @"Change per year";
                dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnDate"].Style.BackColor = System.Drawing.Color.LightBlue;

                dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnDeclination"].Value           = string.Format("{0}°", _MagCalculator.ResultsOfCalculation.Last().Declination.ChangePerYear.ToString("F3"));
                dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnDeclination"].Style.BackColor = System.Drawing.Color.LightBlue;

                dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnInclination"].Value           = string.Format("{0}°", _MagCalculator.ResultsOfCalculation.Last().Inclination.ChangePerYear.ToString("F3"));
                dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnInclination"].Style.BackColor = System.Drawing.Color.LightBlue;

                dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnHorizontalIntensity"].Value           = string.Format("{0} nT", _MagCalculator.ResultsOfCalculation.Last().HorizontalIntensity.ChangePerYear.ToString("F2"));
                dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnHorizontalIntensity"].Style.BackColor = System.Drawing.Color.LightBlue;

                dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnNorthComp"].Value           = string.Format("{0} nT", _MagCalculator.ResultsOfCalculation.Last().NorthComp.ChangePerYear.ToString("F2"));
                dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnNorthComp"].Style.BackColor = System.Drawing.Color.LightBlue;

                dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnEastComp"].Value           = string.Format("{0} nT", _MagCalculator.ResultsOfCalculation.Last().EastComp.ChangePerYear.ToString("F2"));
                dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnEastComp"].Style.BackColor = System.Drawing.Color.LightBlue;

                dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnVerticalComp"].Value           = string.Format("{0} nT", _MagCalculator.ResultsOfCalculation.Last().VerticalComp.ChangePerYear.ToString("F2"));
                dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnVerticalComp"].Style.BackColor = System.Drawing.Color.LightBlue;

                dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnTotalField"].Value           = string.Format("{0} nT", _MagCalculator.ResultsOfCalculation.Last().TotalField.ChangePerYear.ToString("F2"));
                dataGridViewResults.Rows[dataGridViewResults.Rows.Count - 1].Cells["ColumnTotalField"].Style.BackColor = System.Drawing.Color.LightBlue;

                saveToolStripMenuItem.Enabled = true;

                Cursor = Cursors.Default;
            }
        }
Example #36
0
        public static double CalculateAverageConsumptionAMC(int itemId, int storeId, DateTime startDate, DateTime endDate, CalculationOptions option)
        {
            var numberOfDays    = endDate.Subtract(startDate).TotalDays;
            var totalCosumption = CalculateTotalConsumptionAMC(itemId, storeId, startDate, endDate) * 1.0;

            switch (option)
            {
            case CalculationOptions.Daily:
                return(totalCosumption / numberOfDays);

                break;

            case CalculationOptions.Weekly:
                return(totalCosumption / (numberOfDays / 7));

                break;

            case CalculationOptions.Monthly:
                return(totalCosumption / (numberOfDays / 30));

                break;

            case CalculationOptions.Quarterly:
                return(totalCosumption / (numberOfDays / 123));

                break;

            case CalculationOptions.Annual:
                return(totalCosumption / (numberOfDays / 365));

                break;

            default:
                break;
            }
            return(0);
        }