System.Convert.ToDouble(System.DateTime)

Here are the examples of the csharp api System.Convert.ToDouble(System.DateTime) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1083 Examples 7

19 Source : Main.cs
with GNU Lesser General Public License v3.0
from andisturber

public void position(string lat, string lng, string b_0)
        {
            if (_Right == false)
            {
                if (cbGet.Checked == false)
                {
                    Location1.Longitude = double.Parse(lng) + Convert.ToDouble(nudLon.Value);
                    Location1.Lareplacedude = double.Parse(lat) + Convert.ToDouble(nudLat.Value);

                    txtLocation.Text = "经度:" + Location1.Longitude + "\r\n纬度:" + Location1.Lareplacedude + "\r\n位置:" + b_0;
                    if (cbAuto.Checked)
                    {
                        service.UpdateLocation(Location1);
                    }
                }
                else//精准模式 需调用经纬转换API
                {
                    Location1.Longitude = double.Parse(lng);
                    Location1.Lareplacedude = double.Parse(lat);
                    Debug.WriteLine("经度:" + Location1.Longitude + "纬度:" + Location1.Lareplacedude);
                    Location2 = getLocation("http://api.gpsspg.com/convert/coord/?oid=[oid]&key=[key]&from=3&to=0&latlng=" + Location1.Lareplacedude + "," + Location1.Longitude);
                    txtLocation.Text = "经度:" + Location2.Longitude + "\r\n纬度:" + Location2.Lareplacedude + "\r\n位置:" + b_0;
                    if (cbAuto.Checked)
                    {
                        service.UpdateLocation(Location2);
                    }
                }
            }
            else//偏移校正 需调用经纬转换API
            {
                Location1.Longitude = double.Parse(lng);
                Location1.Lareplacedude = double.Parse(lat);
                Location2 = getLocation("http://api.gpsspg.com/convert/coord/?oid=[oid]&key=[key]&from=3&to=0&latlng=" + Location1.Lareplacedude + "," + Location1.Longitude);
                nudLon.Value = Convert.ToDecimal(Location2.Longitude - Location1.Longitude);
                nudLat.Value = Convert.ToDecimal(Location2.Lareplacedude - Location1.Lareplacedude);
                MessageBox.Show("位置偏移已校准。");
                _Right = false;
            }
        }

19 Source : ActivityLegend.cs
with MIT License
from AngeloCresta

private void bubbleSortLegend()
        {
            // Initialize x to the count of the customItems
            int x = myLegend.CustomItems.Count;

            // Create temporary variables
            LegendItem temp;
            int indexTemp;
            DateTime dateTemp;

            // Condition used for second bubble loop
            bool secondCondition = false;

            // Bubble sort
            for (int i = (x - 1); i >= 0; i--)
            {
                for (int j = 1; j <= i; j++)
                {
                    // The condition is based on whether we're aligning to right or left of the chart
                    if ((myLegend.Docking == Docking.Right && myChart.ChartAreas[mySeries[mySeriesreplacedignment[j]].ChartArea].AxisX.IsReversed == false) || (myLegend.Docking == Docking.Left && myChart.ChartAreas[mySeries[mySeriesreplacedignment[j]].ChartArea].AxisX.IsReversed == true))
                    {
                        // If datearray is not empty, use it for comparison instead of the value
                        if (myDateArray == null)
                            secondCondition = (Convert.ToDouble(myLegend.CustomItems[j - 1].Cells[0].Text) > Convert.ToDouble(myLegend.CustomItems[j].Cells[0].Text));
                        else
                            secondCondition = (myDateArray[j - 1] > myDateArray[j]);
                    }
                    else
                    {
                        // If datearray is not empty, use it for comparison instead of the value
                        if (myDateArray == null)
                            secondCondition = (Convert.ToDouble(myLegend.CustomItems[j - 1].Cells[0].Text) < Convert.ToDouble(myLegend.CustomItems[j].Cells[0].Text));
                        else
                            secondCondition = (myDateArray[j - 1] < myDateArray[j]);
                    }

                    if (secondCondition)
                    {
                        // Swap the items
                        temp = myLegend.CustomItems[j - 1];
                        myLegend.CustomItems.Remove(temp);
                        myLegend.CustomItems.Insert(j, temp);

                        // Switch around the indices to reflect a placement change
                        myLegend.CustomItems[j - 1].Cells[1].Name = "ActivityItem" + Convert.ToString(j - 1);
                        myLegend.CustomItems[j].Cells[1].Name = "ActivityItem" + j.ToString();

                        // Move the pointIndex and seriesreplacedignment arrays to reflect the change
                        indexTemp = myPointIndex[j - 1];
                        myPointIndex[j - 1] = myPointIndex[j];
                        myPointIndex[j] = indexTemp;

                        indexTemp = mySeriesreplacedignment[j - 1];
                        mySeriesreplacedignment[j - 1] = mySeriesreplacedignment[j];
                        mySeriesreplacedignment[j] = indexTemp;

                        // Swap the DateArray if it's being used
                        if (myDateArray != null)
                        {
                            dateTemp = myDateArray[j - 1];
                            myDateArray[j - 1] = myDateArray[j];
                            myDateArray[j] = dateTemp;
                        }
                    }
                }
            }
        }

19 Source : IWebsiteScraper.cs
with GNU General Public License v3.0
from AniAPI-Team

private async Task run()
        {
            try
            {
                long lastID = this._animeCollection.Last().Id;

                for (long animeID = 1; animeID < lastID; animeID++)
                {
                    try
                    {
                        _anime = this._animeCollection.Get(animeID);

                        if(_anime == null)
                        {
                            continue;
                        }

                        this.Service.Log($"Website {this.Website.Name} doing {_anime.replacedles[LocalizationEnum.English]}", true);

                        if (!this.animeNeedWork(this.WebsiteForceReload))
                        {
                            throw new ScrapingException($"Website {this.Website.Name} skipped {_anime}");
                        }

                        AnimeMatching matching = null;
                        Browser browser = await ProxyHelper.Instance.GetBrowser();
                        try
                        {
                            using (Page webPage = await ProxyHelper.Instance.GetBestProxy(browser, this.Website.CanBlockRequests))
                            {
                                string animereplacedle = _anime.replacedles.ContainsKey(this.Website.Localization) ?
                                    _anime.replacedles[this.Website.Localization] :
                                    _anime.replacedles[LocalizationEnum.English];

                                matching = await this.GetMatching(webPage, animereplacedle);
                            }
                        }
                        catch { }
                        finally
                        {
                            await browser.CloseAsync();
                        }

                        if (matching == null)
                        {
                            throw new ScrapingException($"Website {this.Website.Name} not found {_anime}");
                        }
                        
                        try
                        {
                            AnimeMatching linked = matching.Linked;
                            
                            await getEpisodes(browser, matching);

                            while (linked != null)
                            {
                                EpisodeMatchings.Clear();

                                await getEpisodes(browser, linked);
                                linked = linked.Linked;
                            }
                        }
                        catch 
                        {
                            throw new ScrapingException($"Website {this.Website.Name} no episode found ({_anime})");
                        }

                        if (this.Website.Official)
                        {
                            _anime.replacedles[this.Website.Localization] = matching.replacedle;
                            _anime.Descriptions[this.Website.Localization] = matching.Description;

                            this._animeCollection.Edit(ref _anime);
                        }
                    }
                    catch(ScrapingException ex) 
                    {
#if DEBUG
                        this.Service.Log(ex.Message);
#endif
                        this.Service.Error(ex.Message);
                    }
                    catch (Exception ex) 
                    {
                        this.Service.Log($"Error: {ex.Message}");
                        this.Service.Log(ex.StackTrace);
                    }
                    finally
                    {
                        this.Progress = Convert.ToDouble(this.Service.GetProgressD(animeID, lastID));
                    }

                    if (this.Service._cancellationToken.IsCancellationRequested)
                    {
                        throw new TaskCanceledException("Process cancellation requested!");
                    }
                }
            }
            catch(TaskCanceledException ex)
            {
                throw;
            }
            catch(Exception ex)
            {
                this.Service.Log($"Error: {ex.Message}");
                this.Service.Log(ex.StackTrace);
            }
            finally
            {
                this.Working = false;
                this.Progress = 100;
            }
        }

19 Source : BuildingBlockProvider.cs
with MIT License
from AnnoDesigner

private bool ParseBuildingBlockerForAnno1800(XmlDoreplacedent ifoDoreplacedent, IBuildingInfo building)
        {
            try
            {
                var xf = 0;
                var zf = 0;
                string xc, zc = ""; // just information for checking line calculated mode

                // Change since 25-05-2021 - Fixing measurements of Buildings Buildblockers. 
                // Insttead of taking one XF * 2 and ZF * 2, it will check now the differences between 2 given XF's and ZF's
                // Get all 4 [Position] childs from xml .ifo doreplacedent
                XmlNode node1 = ifoDoreplacedent.FirstChild?[BUILDBLOCKER].FirstChild;
                XmlNode node2 = ifoDoreplacedent.FirstChild?[BUILDBLOCKER].FirstChild.NextSibling;
                XmlNode node3 = ifoDoreplacedent.FirstChild?[BUILDBLOCKER].FirstChild.NextSibling.NextSibling;
                XmlNode node4 = ifoDoreplacedent.FirstChild?[BUILDBLOCKER].FirstChild.NextSibling.NextSibling.NextSibling;

                //check of the nodes contains data
                if (string.IsNullOrEmpty(node1?.InnerText) || string.IsNullOrEmpty(node2?.InnerText) || string.IsNullOrEmpty(node3?.InnerText) || string.IsNullOrEmpty(node4?.InnerText))
                {
                    Console.WriteLine("-'X' and 'Z' are both 'Null' - Building will be skipped!");
                    return false;
                }

                building.BuildBlocker = new SerializableDictionary<int>();

                //Convert the strings to a Variable and replace the "." for a "," to keep calculatable numbers 
                var xfNormal1 = Convert.ToDouble(node1["xf"].InnerText.Replace(".", ","));
                var zfNormal1 = Convert.ToDouble(node1["zf"].InnerText.Replace(".", ","));
                var xfNormal2 = Convert.ToDouble(node2["xf"].InnerText.Replace(".", ","));
                var zfNormal2 = Convert.ToDouble(node2["zf"].InnerText.Replace(".", ","));
                var xfNormal3 = Convert.ToDouble(node3["xf"].InnerText.Replace(".", ","));
                var zfNormal3 = Convert.ToDouble(node3["zf"].InnerText.Replace(".", ","));
                var xfNormal4 = Convert.ToDouble(node4["xf"].InnerText.Replace(".", ","));
                var zfNormal4 = Convert.ToDouble(node4["zf"].InnerText.Replace(".", ","));

                // Calculation mode check highest number minus lowest number
                // example 1:  9 - -2 = 11
                // example 2: 2,5 - -2,5 = 5
                // This will give the right BuildBlocker[X] and BuildBlocker[Y] for all buildings from anno 1800

                // XF Calculation 
                if (xfNormal1 > xfNormal3)
                {
                    xf = Convert.ToInt32(xfNormal1 - xfNormal3);
                    xc = "MA";// just information for checking line calculated mode
                } else
                {
                    xf = Convert.ToInt32(xfNormal3 - xfNormal1);
                    xc = "MB";// just information for checking line calculated mode
                }

                // zf Calculation 
                if (zfNormal1 > zfNormal2)
                {
                    zf = Convert.ToInt32(zfNormal1 - zfNormal2);
                    zc = "MA";// just information for checking line calculated mode
                }
                else if (zfNormal1 == zfNormal2)
                {
                    if (zfNormal1 > zfNormal3)
                    {
                        zf = Convert.ToInt32(zfNormal1 - zfNormal3);
                        zc = "MB";// just information for checking line calculated mode
                    }
                    else
                    {
                        zf = Convert.ToInt32(zfNormal3 - zfNormal1);
                        zc = "MD";// just information for checking line calculated mode
                    }
                }
                else
                {
                    zf = Convert.ToInt32(zfNormal2 - zfNormal1);
                    zc = "MC";// just information for checking line calculated mode
                }

                
                if ((xf == 0 || zf == 0) && building.Identifier != "Trail_05x05") {
                    //when something goes wrong on the measurements, report and stop till a key is hit
                    Console.WriteLine("MEASUREMENTS GOING WRONG!!! CHECK THIS BUILDING");
                    Console.WriteLine(" Node 1 - XF: {0} | ZF: {1} ;\n Node 2 - XF: {2} | ZF: {3} ;\n Node 3 - XF: {4} | ZF: {5} ;\n Node 4 - XF: {6} | ZF: {7}", xfNormal1, zfNormal1, xfNormal2, zfNormal2, xfNormal3, zfNormal3, xfNormal4, zfNormal4);
                    Console.WriteLine("Building measurement is : {0} x {1} (Method {2} and {3})", xf, zf, xc, zc);
                    Console.WriteLine("Press a key to continue");
                    //Console.ReadKey();
                }

                //if both values are zero, then skip building
                if (xf < 1 && zf < 1)
                {
                    Console.WriteLine("-'X' and 'Z' are both 0 - Building will be skipped!");
                    return false;
                }

                if (xf > 0)
                {
                    building.BuildBlocker[X] = Math.Abs(xf);
                }
                else
                {
                    building.BuildBlocker[X] = 1;
                }

                if (zf > 0)
                {
                    building.BuildBlocker[Z] = Math.Abs(zf);
                }
                else
                {
                    building.BuildBlocker[Z] = 1;
                }
            }
            catch (NullReferenceException)
            {
                Console.WriteLine("-BuildBlocker not found, skipping");
                return false;
            }

            return true;
        }

19 Source : DatabaseService.cs
with MIT License
from AntonyCorbett

public BrowserData? GetBrowserData(string url)
        {
            using (var c = CreateConnection())
            using (var cmd = c.CreateCommand())
            {
                Log.Logger.Verbose($"Selecting from browser table {url}");

                cmd.CommandText = "select id, url, zoom from browser where url = @U";
                cmd.Parameters.AddWithValue("@U", url.Trim());

                using (var r = cmd.ExecuteReader())
                {
                    if (r.Read())
                    {
                        var result = new BrowserData
                        {
                            Id = Convert.ToInt32(r["id"]),
                            Url = (string)r["url"],
                            ZoomLevel = Convert.ToDouble(r["zoom"]),
                        };

                        result.Sanitize();
                        return result;
                    }
                }
            }

            return null;
        }

19 Source : Product.cs
with Apache License 2.0
from Appdynamics

public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
        {
            ValidateArguments(arguments, 1);
            var result = 0d;
            var index = 0;
            while (AreEqual(result, 0d) && index < arguments.Count())
            {
                result = CalculateFirsreplacedem(arguments, index++, context);
            }
            result = CalculateCollection(arguments.Skip(index), result, (arg, current) =>
            {
                if (ShouldIgnore(arg)) return current;
                if (arg.ValueIsExcelError)
                {
                    ThrowExcelErrorValueException(arg.ValueAsExcelErrorValue.Type);
                }
                if (arg.IsExcelRange)
                {
                    foreach (var cell in arg.ValueAsRangeInfo)
                    {
                        if(ShouldIgnore(cell, context)) return current;
                        current *= cell.ValueDouble;
                    }
                    return current;
                }
                var obj = arg.Value;
                if (obj != null && IsNumeric(obj))
                {
                    var val = Convert.ToDouble(obj);
                    current *= val;
                }
                return current;
            });
            return CreateResult(result, DataType.Decimal);
        }

19 Source : Len.cs
with Apache License 2.0
from Appdynamics

public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
        {
            ValidateArguments(arguments, 1);
            var length = arguments.First().ValueFirst.ToString().Length;
            return CreateResult(Convert.ToDouble(length), DataType.Integer);
        }

19 Source : DoubleEnumerableArgConverter.cs
with Apache License 2.0
from Appdynamics

public virtual IEnumerable<ExcelDoubleCellValue> ConvertArgsIncludingOtherTypes(IEnumerable<FunctionArgument> arguments)
        {
            return base.FuncArgsToFlatEnumerable(arguments, (arg, argList) =>
            {
                //var cellInfo = arg.Value as EpplusExcelDataProvider.CellInfo;
                //var value = cellInfo != null ? cellInfo.Value : arg.Value;
                if (arg.Value is ExcelDataProvider.IRangeInfo)
                {
                    foreach (var cell in (ExcelDataProvider.IRangeInfo)arg.Value)
                    {
                        var val = new ExcelDoubleCellValue(cell.ValueDoubleLogical, cell.Row);
                        argList.Add(val);
                    }
                }
                else
                {
                    if (arg.Value is double || arg.Value is int || arg.Value is bool)
                    {
                        argList.Add(Convert.ToDouble(arg.Value));
                    }
                    else if (arg.Value is string)
                    {
                        argList.Add(0d);
                    }
                }
            });
        }

19 Source : ExpressionConverter.cs
with Apache License 2.0
from Appdynamics

public Expression FromCompileResult(CompileResult compileResult)
        {
            switch (compileResult.DataType)
            {
                case DataType.Integer:
                    return compileResult.Result is string
                        ? new IntegerExpression(compileResult.Result.ToString())
                        : new IntegerExpression(Convert.ToDouble(compileResult.Result));
                case DataType.String:
                    return new StringExpression(compileResult.Result.ToString());
                case DataType.Decimal:
                    return compileResult.Result is string
                               ? new DecimalExpression(compileResult.Result.ToString())
                               : new DecimalExpression(((double) compileResult.Result));
                case DataType.Boolean:
                    return compileResult.Result is string
                               ? new BooleanExpression(compileResult.Result.ToString())
                               : new BooleanExpression((bool) compileResult.Result);
                //case DataType.Enumerable:
                //    return 
                case DataType.ExcelError:
                    //throw (new OfficeOpenXml.FormulaParsing.Exceptions.ExcelErrorValueException((ExcelErrorValue)compileResult.Result)); //Added JK
                    return compileResult.Result is string
                        ? new ExcelErrorExpression(compileResult.Result.ToString(),
                            ExcelErrorValue.Parse(compileResult.Result.ToString()))
                        : new ExcelErrorExpression((ExcelErrorValue) compileResult.Result);
                case DataType.Empty:
                   return new IntegerExpression(0); //Added JK

            }
            return null;
        }

19 Source : ExcelWorkbook.cs
with Apache License 2.0
from Appdynamics

private void SetNameElement(ExcelNamedRange name, XmlElement elem)
		{
			if (name.IsName)
			{
				if (string.IsNullOrEmpty(name.NameFormula))
				{
					if ((TypeCompat.IsPrimitive(name.NameValue) || name.NameValue is double || name.NameValue is decimal))
					{
						elem.InnerText = Convert.ToDouble(name.NameValue, CultureInfo.InvariantCulture).ToString("R15", CultureInfo.InvariantCulture); 
					}
					else if (name.NameValue is DateTime)
					{
						elem.InnerText = ((DateTime)name.NameValue).ToOADate().ToString(CultureInfo.InvariantCulture);
					}
					else
					{
						elem.InnerText = "\"" + name.NameValue.ToString() + "\"";
					}                                
				}
				else
				{
					elem.InnerText = name.NameFormula;
				}
			}
			else
			{
                elem.InnerText = name.FullAddressAbsolute;
			}
		}

19 Source : Calculation.cs
with Apache License 2.0
from Appdynamics

[TestMethod, Ignore]
        public void CalulationValidationExcel()
        {
#if Core
            var dir = AppContext.BaseDirectory;
            dir = Directory.GetParent(dir).Parent.Parent.Parent.FullName;
#else
            var dir = AppDomain.CurrentDomain.BaseDirectory;
#endif
            var pck = new ExcelPackage(new FileInfo(Path.Combine(dir, "Workbooks", "FormulaTest.xlsx")));

            var ws = pck.Workbook.Worksheets["ValidateFormulas"];
            var fr = new Dictionary<string, object>();
            foreach (var cell in ws.Cells)
            {
                if (!string.IsNullOrEmpty(cell.Formula))
                {
                    fr.Add(cell.Address, cell.Value);
                }
            }
            pck.Workbook.Calculate();
            var nErrors = 0;
            var errors = new List<Tuple<string, object, object>>();
            foreach (var adr in fr.Keys)
            {
                try
                {
                    if (fr[adr] is double && ws.Cells[adr].Value is double)
                    {
                        var d1 = Convert.ToDouble(fr[adr]);
                        var d2 = Convert.ToDouble(ws.Cells[adr].Value);
                        if (Math.Abs(d1 - d2) < 0.0001)
                        {
                            continue;
                        }
                        else
                        {
                            replacedert.AreEqual(fr[adr], ws.Cells[adr].Value);
                        }
                    }
                    else
                    {
                        replacedert.AreEqual(fr[adr], ws.Cells[adr].Value);
                    }
                }
                catch
                {
                    errors.Add(new Tuple<string, object, object>(adr, fr[adr], ws.Cells[adr].Value));
                    nErrors++;
                }
            }
		}

19 Source : Calculation.cs
with Apache License 2.0
from Appdynamics

private string GetOutput(string file)
        {
            using (var pck = new ExcelPackage(new FileInfo(file)))
            {
                var fr = new Dictionary<string, object>();
                foreach (var ws in pck.Workbook.Worksheets)
                {
                    if (!(ws is ExcelChartsheet))
                    {
                        foreach (var cell in ws.Cells)
                        {
                            if (!string.IsNullOrEmpty(cell.Formula))
                            {
                                fr.Add(ws.PositionID.ToString() + "," + cell.Address, cell.Value);
                                ws.SetValueInner(cell.Start.Row, cell.Start.Column, null);
                            }
                        }
                    }
                }

                pck.Workbook.Calculate();
                var nErrors = 0;
                var errors = new List<Tuple<string, object, object>>();
                ExcelWorksheet sheet=null;
                string adr="";
                var fileErr = new System.IO.StreamWriter(new FileStream("c:\\temp\\err.txt",FileMode.Append));
                foreach (var cell in fr.Keys)
                {
                    try
                    {
                        var spl = cell.Split(',');
                        var ix = int.Parse(spl[0]);
                        sheet = pck.Workbook.Worksheets[ix];
                        adr = spl[1];
                        if (fr[cell] is double && (sheet.Cells[adr].Value is double || sheet.Cells[adr].Value is decimal  || OfficeOpenXml.Compatibility.TypeCompat.IsPrimitive(sheet.Cells[adr].Value)))
                        {
                            var d1 = Convert.ToDouble(fr[cell]);
                            var d2 = Convert.ToDouble(sheet.Cells[adr].Value);
                            //if (Math.Abs(d1 - d2) < double.Epsilon)
                            if(double.Equals(d1,d2))
                            {
                                continue;
                            }
                            else
                            {
                                //errors.Add(new Tuple<string, object, object>(adr, fr[cell], sheet.Cells[adr].Value));
                                fileErr.WriteLine("Diff cell " + sheet.Name + "!" + adr +"\t" + d1.ToString("R15") + "\t" + d2.ToString("R15"));
                            }
                        }
                        else
                        {
                            if ((fr[cell]??"").ToString() != (sheet.Cells[adr].Value??"").ToString())
                            {
                                fileErr.WriteLine("String?  cell " + sheet.Name + "!" + adr + "\t" + (fr[cell] ?? "").ToString() + "\t" + (sheet.Cells[adr].Value??"").ToString());
                            }
                            //errors.Add(new Tuple<string, object, object>(adr, fr[cell], sheet.Cells[adr].Value));
                        }
                    }
                    catch (Exception e)
                    {                        
                        fileErr.WriteLine("Exception cell " + sheet.Name + "!" + adr + "\t" + fr[cell].ToString() + "\t" + sheet.Cells[adr].Value +  "\t" + e.Message);
                        fileErr.WriteLine("***************************");
                        fileErr.WriteLine(e.ToString());
                        nErrors++;
                    }
                }
                fileErr.Close();
                return nErrors.ToString();
            }
        }

19 Source : UnaryExpressionNode.cs
with MIT License
from areller

public override ExpressionNode Simplify()
        {
            if (Operator == UnaryExpressionOperator.Minus)
            {
                if (Operand.Type == RedILNodeType.Constant)
                {
                    var constant = (ConstantValueNode) Operand;
                    if (constant.DataType == DataValueType.Integer)
                    {
                        return new ConstantValueNode(constant.DataType, -Convert.ToInt64(constant.Value));
                    }
                    else if (constant.DataType == DataValueType.Float)
                    {
                        return new ConstantValueNode(constant.DataType, -Convert.ToDouble(constant.Value));
                    }
                }
                else if (Operand.Type == RedILNodeType.UnaryExpression)
                {
                    var unary = (UnaryExpressionNode) Operand;
                    if (unary.Operator == UnaryExpressionOperator.Minus)
                        return unary.Operand;
                }
            }
            else if (Operator == UnaryExpressionOperator.Not)
            {
                if (Operand.Type == RedILNodeType.Constant)
                {
                    var constant = (ConstantValueNode) Operand;
                    if (constant.DataType == DataValueType.Boolean)
                    {
                        return new ConstantValueNode(Operand.DataType, !((bool) constant.Value));
                    }
                }
                else if (Operand.Type == RedILNodeType.UnaryExpression)
                {
                    var unary = (UnaryExpressionNode) Operand;
                    if (unary.Operator == UnaryExpressionOperator.Not)
                        return unary.Operand;
                }
                else if (Operand.Type == RedILNodeType.BinaryExpression)
                {
                    var binary = (BinaryExpressionNode) Operand;
                    if (binary.Operator == BinaryExpressionOperator.Equal)
                        return new BinaryExpressionNode(binary.DataType, BinaryExpressionOperator.NotEqual, binary.Left,
                            binary.Right);
                    else if (binary.Operator == BinaryExpressionOperator.NotEqual)
                        return new BinaryExpressionNode(binary.DataType, BinaryExpressionOperator.Equal, binary.Left,
                            binary.Right);
                    else if (binary.Operator == BinaryExpressionOperator.Less)
                        return new BinaryExpressionNode(binary.DataType, BinaryExpressionOperator.GreaterEqual,
                            binary.Left, binary.Right);
                    else if (binary.Operator == BinaryExpressionOperator.Greater)
                        return new BinaryExpressionNode(binary.DataType, BinaryExpressionOperator.LessEqual,
                            binary.Left, binary.Right);
                    else if (binary.Operator == BinaryExpressionOperator.LessEqual)
                        return new BinaryExpressionNode(binary.DataType, BinaryExpressionOperator.Greater, binary.Left,
                            binary.Right);
                    else if (binary.Operator == BinaryExpressionOperator.GreaterEqual)
                        return new BinaryExpressionNode(binary.DataType, BinaryExpressionOperator.Less, binary.Left,
                            binary.Right);
                }
            }

            return this;
        }

19 Source : BinaryExpressionNode.cs
with MIT License
from areller

private ExpressionNode SimplifyArithmatic(BinaryExpressionOperator op, ExpressionNode left,
            ExpressionNode right)
        {
            if (left.Type == RedILNodeType.Constant && right.Type == RedILNodeType.Constant)
            {
                var leftC = (ConstantValueNode) left;
                var rightC = (ConstantValueNode) right;
                var isInteger = left.DataType == DataValueType.Integer && right.DataType == DataValueType.Integer;
                var dataType = isInteger ? DataValueType.Integer : DataValueType.Float;
                var leftVal = isInteger ? Convert.ToInt64(leftC.Value) : Convert.ToDouble(leftC.Value);
                var rightVal = isInteger ? Convert.ToInt64(rightC.Value) : Convert.ToDouble(rightC.Value);
                switch (Operator)
                {
                    case BinaryExpressionOperator.Add:
                        return new ConstantValueNode(dataType, leftVal + rightVal);
                    case BinaryExpressionOperator.Subtract:
                        return new ConstantValueNode(dataType, leftVal - rightVal);
                    case BinaryExpressionOperator.Multiply:
                        return new ConstantValueNode(dataType, leftVal * rightVal);
                    case BinaryExpressionOperator.Divide:
                        return new ConstantValueNode(dataType, leftVal / rightVal);
                    case BinaryExpressionOperator.Modulus:
                        return new ConstantValueNode(dataType, leftVal %  rightVal);
                    case BinaryExpressionOperator.Less:
                        return new ConstantValueNode(DataValueType.Boolean, leftVal < rightVal);
                    case BinaryExpressionOperator.Greater:
                        return new ConstantValueNode(DataValueType.Boolean, leftVal > rightVal);
                    case BinaryExpressionOperator.LessEqual:
                        return new ConstantValueNode(DataValueType.Boolean, leftVal <= rightVal);
                    case BinaryExpressionOperator.GreaterEqual:
                        return new ConstantValueNode(DataValueType.Boolean, leftVal >= rightVal);
                }
            }

            return this;
        }

19 Source : OptionsWindow.xaml.cs
with GNU General Public License v3.0
from armandoalonso

public void OnExit()
        {
            if (OptionsManager.CurrentOptions != null)
            {
                OptionsManager.CurrentOptions = new Options
                {
                    CompilePath = !string.IsNullOrWhiteSpace(CompilePathText.Text) ? CompilePathText.Text : OptionsManager.DefaultOptions.CompilePath,
                    ExportPath = !string.IsNullOrWhiteSpace(ExportPathText.Text) ? ExportPathText.Text : OptionsManager.DefaultOptions.ExportPath ,
                    DataPath = !string.IsNullOrWhiteSpace(DataPathText.Text) ? DataPathText.Text : OptionsManager.DefaultOptions.DataPath,
                    DefaultAuthor = !string.IsNullOrWhiteSpace(DefaultAuthorTextBox.Text) ? DefaultAuthorTextBox.Text : OptionsManager.DefaultOptions.DefaultAuthor,
                    C3AddonPath = !string.IsNullOrWhiteSpace(C3AddonPathText.Text) ? C3AddonPathText.Text : OptionsManager.DefaultOptions.C3AddonPath,
                    FontSize = Convert.ToDouble(FontSizeCombo.Text),
                    FontFamily = !string.IsNullOrWhiteSpace(FontFamilyCombo.Text) ? FontFamilyCombo.Text : OptionsManager.DefaultOptions.FontFamily,
                    ThemeKey = !string.IsNullOrWhiteSpace(ThemeCombo.Text) ? ThemeCombo.Text : OptionsManager.DefaultOptions.ThemeKey,
                    IncludeTimeStampOnExport = IncludeTimeStamp.IsChecked != null && IncludeTimeStamp.IsChecked.Value,
                    OpenC3InWeb = OpenC3InWeb.IsChecked != null && OpenC3InWeb.IsChecked.Value,
                    C3DesktopPath = C3DesktopPathText.Text.Contains(".exe") ? C3DesktopPathText.Text : System.IO.Path.Combine(C3DesktopPathText.Text, "Construct3.exe"),
                    PinMenu = PinMainMenu.IsChecked != null && PinMainMenu.IsChecked.Value,
                    CompileOnSave = CompileOnSave.IsChecked != null && CompileOnSave.IsChecked.Value,
                    ExportSingleFileProject = ExportSingleProjectFile.IsChecked != null && ExportSingleProjectFile.IsChecked.Value,
                    OverwriteGuidOnImport = OverwriteGuidOnImport.IsChecked != null && OverwriteGuidOnImport.IsChecked.Value,
                    RemoveConsoleLogsOnCompile = RemoveConsoleLogsOnCompile.IsChecked != null && RemoveConsoleLogsOnCompile.IsChecked.Value,
                    UseC2ParserService = UseC2ParsingService.IsChecked != null && UseC2ParsingService.IsChecked.Value,
                    BetaUrl = C3BetaUrl.Text,
                    StableUrl = C3StableUrl.Text,
                    OpenConstructInBeta = OpenConstructInBeta.IsChecked != null && OpenConstructInBeta.IsChecked.Value,
                    AutoIncrementVersionOnPublish = AutoIncrementVersionOnPublish.IsChecked != null && AutoIncrementVersionOnPublish.IsChecked.Value,
                    Port = !string.IsNullOrWhiteSpace(DefaultPort.Text) ? DefaultPort.Text : OptionsManager.DefaultOptions.Port,
                    DisableCodeFormatting = DisableCodeFormatting.IsChecked != null && DisableCodeFormatting.IsChecked.Value
            };

                //create exports folder if it does not exists
                if (!System.IO.Directory.Exists(OptionsManager.CurrentOptions.DataPath)) Directory.CreateDirectory(OptionsManager.CurrentOptions.DataPath);
                if (!System.IO.Directory.Exists(OptionsManager.CurrentOptions.ExportPath)) Directory.CreateDirectory(OptionsManager.CurrentOptions.ExportPath);
                if (!System.IO.Directory.Exists(OptionsManager.CurrentOptions.CompilePath)) Directory.CreateDirectory(OptionsManager.CurrentOptions.CompilePath);
                if (!System.IO.Directory.Exists(OptionsManager.CurrentOptions.C3AddonPath)) Directory.CreateDirectory(OptionsManager.CurrentOptions.C3AddonPath);

                //persist options
                OptionsManager.SaveOptions();
            }
        }

19 Source : OptionsWindow.xaml.cs
with GNU General Public License v3.0
from armandoalonso

private void FontSizeCombo_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var size = Convert.ToDouble(FontSizeCombo.Text);
            OptionsManager.CurrentOptions.FontSize = size;
            OptionsManager.SaveOptions();
        }

19 Source : MicrosoftAccountAuthenticationCache.cs
with Apache License 2.0
from artemshuba

public async Task<AccessToken> CheckAndRenewTokenAsync(CancellationToken cancellationToken)
        {
            if (token == null || token.Expiration < DateTime.UtcNow)
            {
                // This is not thread safe. Unfortunately, portable clreplaced library requirements prevent use of
                // asynchronous locking mechanisms. The risk here is authenticating multiple times in parallel
                // which is bad from a performance standpoint but is transparent from a functional standpoint.
                MicrosoftAccountAuthenticationResponse authenticationResponse =
                    await client.AuthenticateAsync(clientId, clientSecret, cancellationToken);
                if (authenticationResponse != null)
                {
                    token = new AccessToken
                    {
                        Token = authenticationResponse.AccessToken,
                        Expiration =
                            DateTime.UtcNow.Add(TimeSpan.FromSeconds(Convert.ToDouble(authenticationResponse.ExpiresIn)))
                    };
                }
            }

            return token;
        }

19 Source : LastFmImage.cs
with Apache License 2.0
from artemshuba

internal static LastFmImage FromJson(JToken json)
        {
            if (json == null)
                throw new ArgumentException("Json can not be null.");

            var result = new LastFmImage();
            var sizeToken = json.SelectToken("sizes.size");
            if (sizeToken != null)
            {
                foreach (var size in sizeToken.Children())
                {
                    switch (size["name"].Value<string>())
                    {
                        case "small":
                            result.Small = size["#text"].Value<string>();
                            result.Width = Convert.ToDouble(size["width"].Value<string>());
                            result.Height = Convert.ToDouble(size["height"].Value<string>());
                            break;
                        case "medium":
                            result.Medium = size["#text"].Value<string>();
                            result.Width = Convert.ToDouble(size["width"].Value<string>());
                            result.Height = Convert.ToDouble(size["height"].Value<string>());
                            break;
                        case "large":
                            result.Large = size["#text"].Value<string>();
                            result.Width = Convert.ToDouble(size["width"].Value<string>());
                            result.Height = Convert.ToDouble(size["height"].Value<string>());
                            break;
                        case "extralarge":
                            result.ExtraLarge = size["#text"].Value<string>();
                            result.Width = Convert.ToDouble(size["width"].Value<string>());
                            result.Height = Convert.ToDouble(size["height"].Value<string>());
                            break;
                        case "original":
                            result.Original = size["#text"].Value<string>();
                            result.Width = Convert.ToDouble(size["width"].Value<string>());
                            result.Height = Convert.ToDouble(size["height"].Value<string>());
                            result.OriginalWidth = Convert.ToDouble(size["width"].Value<string>());
                            result.OriginalHeight = Convert.ToDouble(size["height"].Value<string>());
                            break;
                    }
                }

            }

            return result;
        }

19 Source : CommonHelper.cs
with Apache License 2.0
from aryice

public static double ToDouble(object vals, int mathround = 1, int retentiondecimalnum = 2)
        {
            double revalue = 0;
            try
            {
                revalue = !Convert.IsDBNull(vals) ? Convert.ToDouble(vals) : 0;
                revalue = Math.Round(revalue / mathround, retentiondecimalnum);
                if (revalue == 0)
                {
                    revalue = 0;
                }
            }
            catch
            {
                ;
            }
            return revalue;
        }

19 Source : LottieAnimationView.cs
with Apache License 2.0
from ascora

private static void ScalePropertyChangedCallback(DependencyObject dependencyObject,
            DependencyPropertyChangedEventArgs e)
        {
            if (dependencyObject is LottieAnimationView lottieAnimationView)
                lottieAnimationView._lottieDrawable.Scale = (float)Convert.ToDouble(e.NewValue);
        }

19 Source : LottieAnimationView.cs
with Apache License 2.0
from ascora

private static void SpeedProperyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            if (dependencyObject is LottieAnimationView lottieAnimationView)
                lottieAnimationView._lottieDrawable.Speed = (float)Convert.ToDouble(e.NewValue);
        }

19 Source : LottieAnimationView.cs
with Apache License 2.0
from ascora

private static void FrameRatePropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            if (dependencyObject is LottieAnimationView lottieAnimationView)
                lottieAnimationView._lottieDrawable.FrameRate = (float)Convert.ToDouble(e.NewValue);
        }

19 Source : BillingItemGenerator.cs
with Apache License 2.0
from asc-lab

public List<BillingItem> Generate(ActiveList activeList, PriceList priceList)
        {
            var billingDate = new DateTime(activeList.Year, activeList.Month, 1);
            var billingItems = new List<BillingItem>();

            foreach (var line in activeList.DataLines)
            {
                if (String.IsNullOrWhiteSpace(line))
                    continue;
                
                var benex = Beneficiary.FromCsvLine(line);
                var price = priceList.GetPrice(benex, billingDate);

                billingItems.Add(new BillingItem
                {
                    ParreplacedionKey = $"{activeList.CustomerCode}-{activeList.Year}-{activeList.Month}",
                    RowKey = Guid.NewGuid().ToString(),
                    Timestamp = DateTime.Now,
                    Beneficiary = $"{benex.NationalId} {benex.Name}",
                    ProductCode = benex.ProductCode,
                    Amount = Convert.ToDouble(price)
                });
            }

            return billingItems;
        }

19 Source : Profile.cs
with MIT License
from ASHTeam

public virtual double GetValue(string section, string entry, double defaultValue)
		{
			object value = GetValue(section, entry);
			if (value == null)
				return defaultValue;

			try
			{
				return Convert.ToDouble(value);
			}
			catch 
			{
				return 0;
			}
		}

19 Source : AsposePDFEditorController.cs
with MIT License
from aspose-pdf

[HttpPost]
		[Route("api/asposepdfeditor/upload-pic")]
		public IHttpActionResult UploadPic(UploadPicModel uploadPicModel)
		{
			var fullPath = Path.Combine(Config.Configuration.WorkingDirectory, "Editor", uploadPicModel.doreplacedentId);
			var downloadFileName = "doreplacedent.pdf";
			var doreplacedentFileName = Path.Combine(Config.Configuration.WorkingDirectory, "Editor", uploadPicModel.doreplacedentId, downloadFileName);
			Doreplacedent doc = new Doreplacedent(doreplacedentFileName);

			//Create image stamp
			ImageStamp imageStamp = new ImageStamp(HttpContext.Current.Server.MapPath("/img/Test.png"));

			for (int i = 0; i < uploadPicModel.shapes.Count; i++)
			{
				//create stamp
				Aspose.Pdf.Facades.Stamp stamp = new Aspose.Pdf.Facades.Stamp();

				float shapeX = (uploadPicModel.shapes[i].x * 72 / 150) / (float)Convert.ToDouble(uploadPicModel.shapes[i].ratio);
				float shapeY = (uploadPicModel.shapes[i].y * 72 / 150) / (float)Convert.ToDouble(uploadPicModel.shapes[i].ratio);
				float shapeW = (uploadPicModel.shapes[i].w * 72 / 150) / (float)Convert.ToDouble(uploadPicModel.shapes[i].ratio);
				float shapeH = (uploadPicModel.shapes[i].h * 72 / 150) / (float)Convert.ToDouble(uploadPicModel.shapes[i].ratio);

				double yaxis = (float)(doc.Pages[uploadPicModel.shapes[i].p].Rect.URY - (shapeH + shapeY));

				var isSpecial = true;//regexItem.IsMatch(uploadPicModel.shapes[i].imName);

				if (uploadPicModel.shapes[i].Itype == "highlight" || uploadPicModel.shapes[i].Itype == "image")
				{

					imageStamp = uploadPicModel.shapes[i].Itype == "highlight"
						? new ImageStamp(HttpContext.Current.Server.MapPath("/img/test.png"))
						: new ImageStamp(fullPath + uploadPicModel.shapes[i].imName);

					imageStamp.Background = false;
					imageStamp.XIndent = (float)(shapeX);
					imageStamp.YIndent = (float)(yaxis);
					imageStamp.Height = shapeH;
					imageStamp.Width = shapeW;

					//Add stamp to particular page
					doc.Pages[uploadPicModel.shapes[i].p].AddStamp(imageStamp);
				}
				else if (uploadPicModel.shapes[i].Itype == "text")
				{
					//create text stamp
					TextStamp textStamp = new TextStamp(uploadPicModel.shapes[i].t);
					textStamp.XIndent = (float)(shapeX);
					textStamp.YIndent = (float)(yaxis);
					//rotate stamp
					textStamp.RotateAngle = 360 - (Convert.ToDouble(uploadPicModel.shapes[i].fieldType) * 180 / Math.PI);

					//set text properties
					textStamp.TextState.Font = FontRepository.FindFont(uploadPicModel.shapes[i].n);
					textStamp.TextState.FontSize = Convert.ToInt32(uploadPicModel.shapes[i].s) * 0.75f;

					if (uploadPicModel.shapes[i].wt == "bold")
					{
						textStamp.TextState.FontStyle = FontStyles.Bold;
					}

					if (uploadPicModel.shapes[i].st == "italic")
					{
						textStamp.TextState.FontStyle = FontStyles.Italic;
					}


					textStamp.TextState.ForegroundColor = GetColor(uploadPicModel.shapes[i].c);
					//add stamp to particular page
					doc.Pages[uploadPicModel.shapes[i].p].AddStamp(textStamp);

				}
				else if (uploadPicModel.shapes[i].Itype == "field" && isSpecial)
				{
					if (uploadPicModel.shapes[i].fieldType == "Text")
					{
						// Get a field
						TextBoxField textBoxField = doc.Form.Fields[Convert.ToInt32(uploadPicModel.shapes[i].imName)] as TextBoxField;
						// Modify field value
						textBoxField.Value = uploadPicModel.shapes[i].t;

					}
					else if (uploadPicModel.shapes[i].fieldType == "CheckBox")
					{

						// Get a field
						CheckboxField checkBoxField = doc.Form.Fields[Convert.ToInt32(uploadPicModel.shapes[i].imName)] as CheckboxField;
						if (uploadPicModel.shapes[i].t != "")
							// Modify field value
							checkBoxField.Checked = Convert.ToBoolean(uploadPicModel.shapes[i].t);
					}
					else if (uploadPicModel.shapes[i].fieldType == "Radio")
					{
						RadioButtonOptionField field = (RadioButtonOptionField)doc.Form.Fields[Convert.ToInt32(uploadPicModel.shapes[i].imName)];

						RadioButtonField rbf = (RadioButtonField)field.Parent;
						if (Convert.ToBoolean(uploadPicModel.shapes[i].t))
						{
							rbf.Selected = rbf.Options[field.OptionName].Index;

						}
						else
						{
							field.ActiveState = "Off";

						}
					}
					else if (uploadPicModel.shapes[i].fieldType == "ComboBox")
					{

						// Get a field
						ComboBoxField comboBoxField = doc.Form.Fields[Convert.ToInt32(uploadPicModel.shapes[i].imName)] as ComboBoxField;
						var values = uploadPicModel.shapes[i].t.Split(new[] { "^^^" }, StringSplitOptions.None)[0];

						foreach (var item in comboBoxField.Options.Cast<Option>())
						{
							if (item.Value == values)
							{

								comboBoxField.Selected = item.Index;
							}
						}
					}
				}

			}

			doc.Save( Config.Configuration.OutputDirectory + "/Export.pdf");

			return Ok(new DocStatusModel());
		}

19 Source : AddWatermarkPdf.aspx.cs
with MIT License
from aspose-pdf

protected void btnAddWatermark_Click(object sender, EventArgs e)
		{
            if (StampType.Value.Contains("text"))
                Page.Validate("settingsTextStamp");
            else
                Page.Validate("settingsImageStamp");

            if (Page.IsValid)
			{				
				pMessage.Attributes.Remove("clreplaced");
				pMessage.InnerHtml = "";

				

				// Check if File is available.
				if ( !string.IsNullOrEmpty(FilePath.Value) && Convert.ToDouble(FileLength.Value) > 0)
				{
					hdnDownloadFileName.Value = hdnDownloadFileURL.Value = "";
					string fn = FilePath.Value;					
					try
					{
						 

					    var imageFile = "";
					    var imageFolderName = "";

					    if (StampType.Value.Contains("image"))
					    {

					        if (FileUploadImage.PostedFile != null && FileUploadImage.PostedFile.ContentLength > 0)
					        {
					            
					            try
					            {
									var files = UploadFiles(FileUploadImage);
									if (files != null && files.Count == 1)
									{
										
											imageFile = files[0].FileName; 
											imageFolderName = files[0].FolderId;

									}
					            }
					            catch (Exception ex)
					            {
					                pMessage.Visible = true;
					                pMessage.InnerHtml = "Error: " + ex.Message;
					                pMessage.Attributes.Add("clreplaced", "alert alert-danger");
					            }
					        }


                        }




                        {
							
							Response response = null;
							AsposePdfWatermark _asposePdfWatermark = new AsposePdfWatermark();

                            if (StampType.Value.Contains("text"))
                            {
								response = _asposePdfWatermark.AddTextStamp(FilePath.Value, FolderId.Value, txreplacedermark.Value,
									hdnToValue.Value.ToLower(), pickcolor.Value.Replace("#", ""), fontFamily.SelectedValue, float.Parse( fontSize.Text), fontStyle.SelectedValue, double.Parse( textAngle.Text));

								
                            }
                            else
                            {
								response = _asposePdfWatermark.AddImageStamp(FilePath.Value, FolderId.Value, imageFile,
									imageFolderName, hdnToValue.Value.ToLower(), ImageColor.SelectedValue, double.Parse(ImageAngle.Text), double.Parse(ZoomFactor.Text));
								
                            }                
							

							if (response.StatusCode == 200)
							{
								//string url = HttpUtility.UrlEncode("FileName=" + response.FileName + "&Time=" + DateTime.Now.ToString());
								string url = Configuration.FileDownloadLink + "?fileName=" + HttpUtility.UrlEncode(response.FileName) ;
								if (response.FolderName != "")
								{
									url += "&folderName=" + response.FolderName;
								}
								litDownloadNow.Text = "<a target=\"_blank\" href=\"" + url + "\" clreplaced=\"btn btn-success btn-lg\">" + Resources["DownLoadNow"] + " <i clreplaced=\"fa fa-download\"></i></a>";
								hdnDownloadFileName.Value = response.FileName;
								hdnDownloadFileURL.Value = url;
							    PageViewId.ActiveViewIndex = 2;
                                //ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ShowfileSendEmail()", true);

							}
							else
							{
								pMessage.Visible = true;
								pMessage.InnerHtml = response.Status;
								pMessage.Attributes.Add("clreplaced", "alert alert-danger");
							}
						}
					}
					catch (Exception ex)
					{
						pMessage.Visible = true;
						pMessage.InnerHtml = "Error: " + ex.Message;
						pMessage.Attributes.Add("clreplaced", "alert alert-danger");
					}
				}
				else
				{
					pMessage.Visible = true;
					pMessage.InnerHtml = Resources["FileSelectMessage"];
					pMessage.Attributes.Add("clreplaced", "alert alert-danger");
				}
			}
		}

19 Source : Vector.cs
with MIT License
from Autodesk

public void GetXYVectors(ref Vector xVector, ref Vector yVector)
        {
            //Normalize this vector
            Vector zVector = Clone();
            zVector.Normalize();

            //Dont quite understand the rest...
            Vector x = null;
            Vector y = null;

            if ((Math.Abs(Convert.ToDouble(zVector.K)) >= Math.Abs(Convert.ToDouble(zVector.I))) &
                (Math.Abs(Convert.ToDouble(zVector.K)) >= Math.Abs(Convert.ToDouble(zVector.J))))
            {
                x = new Vector(1, 0, -1.0 * zVector.J / zVector.K);
            }
            else if ((Math.Abs(Convert.ToDouble(zVector.J)) >= Math.Abs(Convert.ToDouble(zVector.I))) &
                     (Math.Abs(Convert.ToDouble(zVector.J)) >= Math.Abs(Convert.ToDouble(zVector.K))))
            {
                x = new Vector(1, -1.0 * zVector.K / zVector.J, 0);
            }
            else if (zVector.I != 0)
            {
                x = new Vector(-1.0 * zVector.K / zVector.I, 0, 1);
            }

            x.Normalize();
            y = CrossProduct(zVector, x);

            y.Normalize();
            x = CrossProduct(y, zVector);

            xVector = x;
            yVector = y;
        }

19 Source : Workplane.cs
with MIT License
from Autodesk

private Tuple<double[,], double[]> GetRotationMatrixAndTranslationFromMatrixFile(File matrixFile)
        {
            int NUMBER_OF_ROWS_IN_TRANSFORMATION_MATRIX = 4;
            int NUMBER_OF_COLUMNS_IN_TRANSFORMATION_MATRIX = 4;
            int NUMBER_OF_ROWS_IN_ROTATION_MATRIX = 3;
            int NUMBER_OF_COLUMNS_IN_ROTATION_MATRIX = 3;
            int NUMBER_OF_ELEMENTS_IN_TRANSLATION_VECTOR = 3;

            var rows = matrixFile.ReadTextLines();

            if (rows.Count() != NUMBER_OF_ROWS_IN_TRANSFORMATION_MATRIX)
            {
                throw new ArgumentException(
                    $"Failed to load 'matrix' file. The file should have {NUMBER_OF_ROWS_IN_TRANSFORMATION_MATRIX} lines. The first line should be xAxis.i|yAxis.i|zAxis.i|x. The second line should be xAxis.j|yAxis.j|zAxis.j|y. The third line should be xAxis.k|yAxis.k|zAxis.k|z");
            }

            double[,] rotationMatrix = new double[NUMBER_OF_ROWS_IN_ROTATION_MATRIX, NUMBER_OF_COLUMNS_IN_ROTATION_MATRIX];
            double[] translation = new double[NUMBER_OF_ELEMENTS_IN_TRANSLATION_VECTOR];

            // The expected format of the transformation matrix is the following:
            //xAxis.i|yAxis.i|zAxis.i|x
            //xAxis.j|yAxis.j|zAxis.j|y
            //xAxis.k|yAxis.k|zAxis.k|z
            //0|0|0|1

            // The 1st column is the new x vector relative to World
            // The 2nd column is the new y vector relative to World
            // The 3rd column is the new z vector relative to World
            // The 4th column is the new origin position relative to World
            for (int l = 0; l < NUMBER_OF_ROWS_IN_ROTATION_MATRIX; l++)
            {
                var rowInvariant = rows[l].ToLowerInvariant();
                var rowItems = rowInvariant.Split('|');

                if (rowItems.Count() != NUMBER_OF_COLUMNS_IN_TRANSFORMATION_MATRIX)
                {
                    throw new ArgumentException(
                        $"Failed to load 'matrix' file. The file should have per line {NUMBER_OF_COLUMNS_IN_TRANSFORMATION_MATRIX} numeric values separated by '|'.");
                }

                for (int c = 0; c < NUMBER_OF_COLUMNS_IN_TRANSFORMATION_MATRIX; c++)
                {
                    double rowValue;
                    try
                    {
                        rowValue = Convert.ToDouble(rowItems[c]);
                        if (c == 3)
                        {
                            // In the 4th column are the translation values
                            translation[l] = rowValue;
                        }
                        else
                        {
                            rotationMatrix[l, c] = rowValue;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new ArgumentException($"Invalid MATRIX file. No numeric value found in : {rowItems[c]}", ex);
                    }
                }
            }

            return new Tuple<double[,], double[]>(rotationMatrix, translation);
        }

19 Source : AsciiStlFileReader.cs
with MIT License
from Autodesk

public List<DMTModel> ReadFile(File file, IDMTModelFilter filter)
        {
            if (file.Exists == false)
            {
                throw new DMTFileException(DMTFileError.FileDoesNotExist);
            }

            var blocksIn = new List<DMTTriangleBlock>();
            var blocksOut = new List<DMTTriangleBlock>();
            var blockIn = new DMTTriangleBlock();
            var blockOut = new DMTTriangleBlock();
            var vertices = new List<Point>();

            foreach (var strLine in file.ReadTextLines())
            {
                if (strLine.Trim().StartsWith("vertex "))
                {
                    //Add position
                    var strCoords = strLine.Trim().Split(' ');
                    var intCounter = 0;
                    double x = 0;
                    double y = 0;
                    double z = 0;
                    foreach (var strCoord in strCoords)
                    {
                        if (Information.IsNumeric(strCoord))
                        {
                            if (intCounter == 0)
                            {
                                x = Convert.ToDouble(strCoord);
                            }
                            else if (intCounter == 1)
                            {
                                y = Convert.ToDouble(strCoord);
                            }
                            else
                            {
                                z = Convert.ToDouble(strCoord);
                            }
                            intCounter += 1;
                        }
                    }

                    vertices.Add(new Point(x, y, z));
                }
                else if (strLine.Trim().StartsWith("endloop"))
                {
                    if (filter.CanAddTriangle(vertices.ElementAt(0), vertices.ElementAt(1), vertices.ElementAt(2)))
                    {
                        blockIn.AddTriangle(vertices.ElementAt(0), vertices.ElementAt(1), vertices.ElementAt(2));
                    }
                    else
                    {
                        blockOut.AddTriangle(vertices.ElementAt(0), vertices.ElementAt(1), vertices.ElementAt(2));
                    }

                    vertices.Clear();
                }
            }

            blocksIn.Add(blockIn);
            blocksOut.Add(blockOut);

            var modelWithinFilter = new DMTModel();
            var modelOutsideFilter = new DMTModel();
            modelWithinFilter.TriangleBlocks.AddRange(blocksIn);
            modelOutsideFilter.TriangleBlocks.AddRange(blocksOut);
            var result = new List<DMTModel>();
            result.Add(modelWithinFilter);
            result.Add(modelOutsideFilter);
            return result;
        }

19 Source : PMProject.cs
with MIT License
from Autodesk

public BoundingBox GetBlockLimits()
        {            
            var tpBlockXmin = _powerMILL.DoCommandEx("PRINT PAR TERSE $Block.Limits.XMin");
            var tpBlockXmax = _powerMILL.DoCommandEx("PRINT PAR TERSE $Block.Limits.XMax");
            var tpBlockYmin = _powerMILL.DoCommandEx("PRINT PAR TERSE $Block.Limits.YMin");
            var tpBlockYmax = _powerMILL.DoCommandEx("PRINT PAR TERSE $Block.Limits.YMax");
            var tpBlockZmin = _powerMILL.DoCommandEx("PRINT PAR TERSE $Block.Limits.ZMin");
            var tpBlockZmax = _powerMILL.DoCommandEx("PRINT PAR TERSE $Block.Limits.ZMax");

            BoundingBox boundingBox = new BoundingBox(Convert.ToDouble(tpBlockXmin), Convert.ToDouble(tpBlockXmax),
                                                      Convert.ToDouble(tpBlockYmin), Convert.ToDouble(tpBlockYmax),
                                                      Convert.ToDouble(tpBlockZmin), Convert.ToDouble(tpBlockZmax));
                        
            return boundingBox;
        }

19 Source : DMTModel.cs
with MIT License
from Autodesk

public List<Point> ProjectPoints(List<Point> pointsToProject, bool projectDownOnly = false)
        {
            // Zone model here in case user forgets.
            ZoneModel();

            // Loop through all the points and for each one find the nearest point in the z axis
            List<Point> projectedPoints = new List<Point>();

            Vector projectionVector = new Vector(0.0, 0.0, -1.0);

            // Work out the size of the zones in the x and y directions
            double minX = 0;
            double minY = 0;

            double xZoneLength = 0;
            double yZoneLength = 0;

            int numXZones = 0;
            int numYZones = 0;

            BoundingBox modelBoundingBox = BoundingBox;
            var _with2 = modelBoundingBox;
            xZoneLength = _with2.XSize / Math.Sqrt(_numberOfZones);
            yZoneLength = _with2.YSize / Math.Sqrt(_numberOfZones);

            numXZones = (int) (_with2.XSize / xZoneLength) + 1;
            numYZones = (int) (_with2.YSize / yZoneLength) + 1;

            minX = _with2.MinX;
            minY = _with2.MinY;

            foreach (Point pointToProject in pointsToProject)
            {
                // First find which zone (row and column) the point is in

                int row = 0;
                int col = 0;

                row = (int) ((pointToProject.X - minX) / xZoneLength);
                col = (int) ((pointToProject.Y - minY) / yZoneLength);

                Point nearestPoint = null;

                if ((row >= 0) & (col >= 0) && row < _zones.Count && col < _zones[row].Count)
                {
                    // Get the zone
                    DMTTriangleZone zone = _zones[row][col];

                    // Now loop through all triangles in the zone
                    double nearest = double.MaxValue;

                    // Loop through all the triangles in the zone
                    foreach (DMTTriangleZoneEntry triangleEntry in zone.Triangles)
                    {
                        //' Get the triangle itself
                        //Dim triangle As DMTTriangle
                        //With triangleEntry
                        //    triangle = CType(_blocks(.Block), DMTTriangleBlock).Triangles(.Triangle)
                        //End With

                        // Check to see if the projection point intersects this triangle
                        Point projectedPoint = null;
                        projectedPoint = ProjectPointToTriangle(pointToProject,
                                                                projectionVector,
                                                                _blocks[triangleEntry.Block].GetVertex1(triangleEntry.Triangle),
                                                                _blocks[triangleEntry.Block].GetVertex2(triangleEntry.Triangle),
                                                                _blocks[triangleEntry.Block].GetVertex3(triangleEntry.Triangle));

                        // If it does then see if it is nearer than any point found so far
                        if (projectedPoint != null)
                        {
                            // Ignore if we are projecting down only and the point is above us
                            if (projectDownOnly && pointToProject.Z < projectedPoint.Z)
                            {
                                continue;
                            }
                            double distance = Math.Abs(Convert.ToDouble(pointToProject.Z - projectedPoint.Z));
                            if (distance < nearest)
                            {
                                // It is the nearest so far
                                nearest = distance;
                                nearestPoint = projectedPoint.Clone();
                            }
                        }
                    }
                }

                // Add the nearest point to the list of output points
                projectedPoints.Add(nearestPoint);
            }

            return projectedPoints;
        }

19 Source : NumericRule.cs
with MIT License
from Avanade

public override Task ValidateAsync(PropertyContext<TEnreplacedy, TProperty> context)
        {
            // Where allowing negatives or the value is null, do nothing; i.e. Nullable<Type>.
            Beef.Check.NotNull(context, nameof(context));

            if (AllowNegatives || Comparer<object>.Default.Compare(context.Value!, null!) == 0)
                return Task.CompletedTask;

            // Convert numeric to a double value.
            double value = Convert.ToDouble(context.Value, System.Globalization.CultureInfo.InvariantCulture);

            // Determine if the value is negative and is/isn't allowed.
            if (!AllowNegatives && value < 0)
                context.CreateErrorMessage(ErrorText ?? ValidatorStrings.AllowNegativesFormat);

            return Task.CompletedTask;
        }

19 Source : PB_TrayTypeController.cs
with MIT License
from awesomedotnetcore

[HttpPost]
        [NoCheckJWT]
        public async Task<AjaxResult> Import(IFormFile file)// file
        {
            string ReturnValue = string.Empty;
            //定义一个bool类型的变量用来做验证
            bool flag = true;
            try
            {
                #region 检查文件
                string fileExt = Path.GetExtension(file.FileName).ToLower();
                //定义一个集合一会儿将数据存储进来,全部一次丢到数据库中保存
                var Data = new List<PB_TrayType>();
                MemoryStream ms = new MemoryStream();
                file.CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);
                IWorkbook book;
                if (fileExt == ".xlsx")
                {
                    book = new XSSFWorkbook(ms);
                }
                else if (fileExt == ".xls")
                {
                    book = new HSSFWorkbook(ms);
                }
                else
                {
                    book = null;
                }
                ISheet sheet = book.GetSheetAt(0);

                int CountRow = sheet.LastRowNum + 1;//获取总行数

                if (CountRow - 1 == 0)
                {
                    return Error("Excel列表数据项为空!");

                }
                #endregion
                #region 循环验证
                for (int i = 1; i < CountRow; i++)
                {
                    //获取第i行的数据
                    var row = sheet.GetRow(i);
                    if (row != null)
                    {
                        //循环的验证单元格中的数据
                        for (int j = 0; j < 6; j++)
                        {
                            if ((j == 4 || j == 5) || (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0))
                            {
                                //return Error(ReturnValue += $"注意第{i + 1}行,第{j + 1}列数据为空。");
                            }
                            else
                            if (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0)
                            {
                                flag = false;
                                return Error(ReturnValue += $"第{i + 1}行,第{j + 1}列数据不能为空。");
                            }
                        }
                    }
                }
                #endregion
                if (flag)
                {
                    for (int i = 1; i < CountRow; i++)//
                    {
                        //实例化实体对象
                        PB_TrayType commodity = new PB_TrayType();
                        var row = sheet.GetRow(i);
                        if (row.GetCell(0) != null && row.GetCell(0).ToString().Trim().Length > 0)
                        {
                            commodity.Id = IdHelper.GetId();
                            commodity.CreatorId = _Op.UserId; //"Admin";//_Op.UserId;
                            commodity.IsZone = false;//默认不启用分区

                            commodity.Code = row.GetCell(0).ToString();
                        }
                        if (row.GetCell(1) != null && row.GetCell(1).ToString().Trim().Length > 0)
                        {
                            commodity.Name = row.GetCell(1).ToString();
                        }
                        if (row.GetCell(2) != null && row.GetCell(2).ToString().Trim().Length > 0)
                        {
                            commodity.Length = Convert.ToDouble(row.GetCell(2).ToString());
                        }
                        if (row.GetCell(3) != null && row.GetCell(3).ToString().Trim().Length > 0)
                        {
                            commodity.Width = Convert.ToDouble(row.GetCell(3).ToString());
                        }
                        if (row.GetCell(4) != null && row.GetCell(4).ToString().Trim().Length > 0)
                        {
                            commodity.High = Convert.ToDouble(row.GetCell(4).ToString());
                        }
                        Data.Add(commodity);
                    }

                    foreach (var item in Data)
                    {
                        if (item.Length == null)
                        {
                            item.Length = null;
                        }
                        if (item.Width == null)
                        {
                            item.Width = null;
                        }
                        if (item.High == null)
                        {
                            item.High = null;
                        }
                    }
                    if (Data.Count > 0)
                    {
                        int j = 1000;
                        for (int i = 0; i < Data.Count; i += 1000)
                        {
                            var cList = new List<PB_TrayType>();
                            cList = Data.Take(j).Skip(i).ToList();
                            j += 1000;
                            await _pB_TrayTypeBus.AddDataExlAsync(cList);
                        }
                        ReturnValue = $"数据导入成功,共导入{CountRow - 1}条数据。";
                    }
                }
                if (!flag)
                {
                    return Error(ReturnValue = "数据存在问题!" + ReturnValue);
                }
            }
            catch (Exception)
            {
                return Error("数据异常!");
            }

            return Success(ReturnValue);

        }

19 Source : TD_CheckController_Partial.cs
with MIT License
from awesomedotnetcore

[HttpPost]
        public async Task<AjaxResult> Preplaced(string Id)
        {
            var _Op = _provider.GetRequiredService<IOperator>();
            var _checkSvc = _provider.GetRequiredService<ITD_CheckDataBusiness>();
            AjaxResult result = new AjaxResult();
            try
            {
                var enreplacedy = await _tD_CheckBus.GetTheDataAsync(Id);
                enreplacedy.Status = 1;
                enreplacedy.AuditeTime = DateTime.Now;
                enreplacedy.AuditUserId = _Op.UserId;

                var checkDataList = await _checkSvc.AllCheckDataListAsync(enreplacedy.Id);

                //库存更新数据
                var localData = (from u in checkDataList
                                 where u.DisNum.HasValue
                                 select new BusinessInfo()
                                 {
                                     ActionType = 2,
                                     BarCode = u.BarCode,
                                     BatchNo = u.BatchNo,
                                     LocalId = u.localId,
                                     MaterialId = u.MaterialId,
                                     MeasureId = u.MeasureId,
                                     Num = Convert.ToDouble(u.DisNum),
                                     StorId = u.StorId,
                                     ZoneId = u.ZoneId,
                                     TrayId = u.TrayId
                                 }).ToList();

                //台账数据
                var recordData = (from u in checkDataList
                                  where u.DisNum.HasValue
                                  select new IT_RecordBook()
                                  {
                                      Id = IdHelper.GetId(),
                                      BarCode = u.BarCode,
                                      BatchNo = u.BatchNo,
                                      CreateTime = DateTime.Now,
                                      CreatorId = _Op.UserId,
                                      Deleted = false,
                                      FromLocalId = u.localId,
                                      FromStorId = u.StorId,
                                      MaterialId = u.MaterialId,
                                      MeasureId = u.MeasureId,
                                      Num = System.Math.Abs(Convert.ToDouble(u.DisNum)),
                                      RefCode = enreplacedy.RefCode,
                                      Type = Convert.ToDouble(u.DisNum) > 0 ? "Panying" : "Deficit"
                                  }).ToList();

                await _tD_CheckBus.PreplacedHandleAsync(enreplacedy, localData, recordData);
                result.Success = true;
            }
            catch (Exception e)
            {
                result.Success = false;
                result.ErrorCode = 502;
                result.Msg = e.Message;
            }

            return result;
        }

19 Source : PB_LocationController.cs
with MIT License
from awesomedotnetcore

[HttpPost]
        [NoCheckJWT]
        public async Task<AjaxResult> Import(IFormFile file)// file
        {
            string ReturnValue = string.Empty;
            //定义一个bool类型的变量用来做验证
            bool flag = true;
            try
            {
                string fileExt = Path.GetExtension(file.FileName).ToLower();
                //定义一个集合一会儿将数据存储进来,全部一次丢到数据库中保存
                var Data = new List<PB_Location>();
                MemoryStream ms = new MemoryStream();
                file.CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);
                IWorkbook book;
                if (fileExt == ".xlsx")
                {
                    book = new XSSFWorkbook(ms);
                }
                else if (fileExt == ".xls")
                {
                    book = new HSSFWorkbook(ms);
                }
                else
                {
                    book = null;
                }
                ISheet sheet = book.GetSheetAt(0);

                int CountRow = sheet.LastRowNum + 1;//获取总行数

                if (CountRow - 1 == 0)
                {
                    return Error("Excel列表数据项为空!");

                }
                #region 循环验证
                for (int i = 1; i < CountRow; i++)
                {
                    //获取第i行的数据
                    var row = sheet.GetRow(i);
                    if (row != null)
                    {
                        //循环的验证单元格中的数据
                        for (int j = 0; j < 6; j++)
                        {
                            if ((j == 4 || j == 5) || (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0))
                            {
                                //return Error(ReturnValue += $"注意第{i + 1}行,第{j + 1}列数据为空。");
                            }
                            else
                            if (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0)
                            {
                                flag = false;
                                return Error(ReturnValue += $"第{i + 1}行,第{j + 1}列数据不能为空。");
                            }
                        }
                    }
                }
                #endregion
                if (flag)
                {
                    for (int i = 1; i < CountRow; i++)//
                    {
                        //实例化实体对象
                        PB_Location commodity = new PB_Location();
                        var row = sheet.GetRow(i);
                        if (row.GetCell(0) != null && row.GetCell(0).ToString().Trim().Length > 0)
                        {
                            commodity.Id = IdHelper.GetId();
                            commodity.CreatorId = _Op.UserId; //"Admin";//_Op.UserId;
                            commodity.IsForbid = true;//导入默认启用
                            commodity.IsDefault = false;//导入无默认

                            commodity.Code = row.GetCell(0).ToString();

                        }
                        if (row.GetCell(1) != null && row.GetCell(1).ToString().Trim().Length > 0)
                        {
                            commodity.Name = row.GetCell(1).ToString();
                        }
                        if (row.GetCell(2) != null && row.GetCell(2).ToString().Trim().Length > 0)
                        {
                            commodity.StorId = row.GetCell(2).ToString();
                        }
                        if (row.GetCell(3) != null && row.GetCell(3).ToString().Trim().Length > 0)
                        {
                            commodity.AreaId = row.GetCell(3).ToString();
                        }
                        if (row.GetCell(4) != null && row.GetCell(4).ToString().Trim().Length > 0)
                        {
                            commodity.LanewayId = row.GetCell(4).ToString().ToString();
                        }
                        if (row.GetCell(5) != null && row.GetCell(5).ToString().Trim().Length > 0)
                        {
                            commodity.RackId = row.GetCell(5).ToString();
                        }
                        if (row.GetCell(6) != null && row.GetCell(6).ToString().Trim().Length > 0)
                        {
                            commodity.OverVol = Convert.ToDouble(row.GetCell(6).ToString());
                        }
                        Data.Add(commodity);
                    }
                    var listStorCodes = Data.Select(s => s.StorId).Select(s => s.Trim()).Distinct().ToList();
                    var dicStor = _pB_LocationBus.GetQueryable<PB_Storage>().Where(w => listStorCodes.Contains(w.Code)).ToDictionary(k => k.Code, v => v.Id);

                    var listAreaCodes = Data.Select(s => s.AreaId).Select(s => s.Trim()).Distinct().ToList();
                    var dicArea = _pB_LocationBus.GetQueryable<PB_StorArea>().Where(w => listAreaCodes.Contains(w.Code)).ToDictionary(k => k.Code, v => v.Id);


                    var listLanewayCodes = Data.Select(s => s.LanewayId).Select(s => s.Trim()).Distinct().ToList();
                    var dicLaneway = _pB_LocationBus.GetQueryable<PB_Laneway>().Where(w => listLanewayCodes.Contains(w.Code)).ToDictionary(k => k.Code, v => v.Id);

                    var listRackCodes = Data.Select(s => s.RackId).Select(s => s.Trim()).Distinct().ToList();
                    var dicRack = _pB_LocationBus.GetQueryable<PB_Rack>().Where(w => listRackCodes.Contains(w.Code)).ToDictionary(k => k.Code, v => v.Id);

                    foreach (var item in Data)
                    {
                        if (dicStor.ContainsKey(item.StorId.Trim()))
                            item.StorId = dicStor[item.StorId.Trim()];
                        else
                            throw new Exception("仓库编号不存在!");

                        if (dicArea.ContainsKey(item.AreaId.Trim()))
                            item.AreaId = dicArea[item.AreaId.Trim()];
                        else
                            throw new Exception("货区编号不存在!");

                        if (item.LanewayId == null)
                        {
                            item.LanewayId = null;
                        }
                        else if (dicLaneway.ContainsKey(item.LanewayId.Trim()))
                        {
                            item.LanewayId = dicLaneway[item.LanewayId.Trim()];
                        }

                        if (item.RackId == null)
                        {
                            item.RackId = null;
                        }
                        else if (dicRack.ContainsKey(item.RackId.Trim()))
                        {
                            item.RackId = dicRack[item.RackId.Trim()];
                        }

                    }
                    if (Data.Count > 0)
                    {
                        int j = 1000;

                        for (int i = 0; i < Data.Count; i += 1000)

                        {

                            var cList = new List<PB_Location>();

                            cList = Data.Take(j).Skip(i).ToList();

                            j += 1000;

                            await _pB_LocationBus.AddDataExlAsync(cList);

                        }
                        ReturnValue = $"数据导入成功,共导入{CountRow - 1}条数据。";
                    }
                }

                if (!flag)
                {
                    return Error(ReturnValue = "数据存在问题!" + ReturnValue);
                }
            }
            catch (Exception)
            {
                return Error("数据异常!");
            }

            return Success(ReturnValue);

        }

19 Source : PB_MaterialController.cs
with MIT License
from awesomedotnetcore

[HttpPost]
        [NoCheckJWT]
        public async Task<AjaxResult> Import(IFormFile file)// file
        {
            string ReturnValue = string.Empty;
            //定义一个bool类型的变量用来做验证
            bool flag = true;
            try
            {
                #region 检查文件
                string fileExt = Path.GetExtension(file.FileName).ToLower();
                //定义一个集合一会儿将数据存储进来,全部一次丢到数据库中保存
                var Data = new List<PB_Material>();
                MemoryStream ms = new MemoryStream();
                file.CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);
                IWorkbook book;
                if (fileExt == ".xlsx")
                {
                    book = new XSSFWorkbook(ms);
                }
                else if (fileExt == ".xls")
                {
                    book = new HSSFWorkbook(ms);
                }
                else
                {
                    book = null;
                }
                ISheet sheet = book.GetSheetAt(0);

                int CountRow = sheet.LastRowNum + 1;//获取总行数

                if (CountRow - 1 == 0)
                {
                    return Error("Excel列表数据项为空!");

                }
                #endregion
                #region 循环验证
                for (int i = 1; i < CountRow; i++)
                {
                    //获取第i行的数据
                    var row = sheet.GetRow(i);
                    if (row != null)
                    {
                        //循环的验证单元格中的数据
                        for (int j = 0; j < 6; j++)
                        {
                            if ((j == 4 || j == 5) || (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0))
                            {
                                //return Error(ReturnValue += $"注意第{i + 1}行,第{j + 1}列数据为空。");
                            }
                            else
                            if (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0)
                            {
                                flag = false;
                                return Error(ReturnValue += $"第{i + 1}行,第{j + 1}列数据不能为空。");
                            }
                        }
                    }
                }
                #endregion
                if (flag)
                {
                    for (int i = 1; i < CountRow; i++)//
                    {
                        //实例化实体对象
                        PB_Material commodity = new PB_Material();
                        var row = sheet.GetRow(i);
                        if (row.GetCell(0) != null && row.GetCell(0).ToString().Trim().Length > 0)
                        {
                            commodity.Id = IdHelper.GetId();
                            commodity.CreatorId = _Op.UserId; //"Admin";//_Op.UserId;

                            commodity.Code = row.GetCell(0).ToString();

                        }
                        if (row.GetCell(1) != null && row.GetCell(1).ToString().Trim().Length > 0)
                        {
                            commodity.Name = row.GetCell(1).ToString();
                        }
                        if (row.GetCell(2) != null && row.GetCell(2).ToString().Trim().Length > 0)
                        {
                            commodity.BarCode = row.GetCell(2).ToString();
                        }
                        if (row.GetCell(3) != null && row.GetCell(3).ToString().Trim().Length > 0)
                        {
                            commodity.SimpleName = row.GetCell(3).ToString();
                        }
                        if (row.GetCell(4) != null && row.GetCell(4).ToString().Trim().Length > 0)
                        {
                            commodity.MaterialTypeId = row.GetCell(4).ToString();
                        }
                        if (row.GetCell(5) != null && row.GetCell(5).ToString().Trim().Length > 0)
                        {
                            commodity.MeasureId = row.GetCell(5).ToString();
                        }
                        if (row.GetCell(6) != null && row.GetCell(6).ToString().Trim().Length > 0)
                        {
                            commodity.Spec = row.GetCell(6).ToString();
                        }
                        if (row.GetCell(7) != null && row.GetCell(7).ToString().Trim().Length > 0)
                        {
                            commodity.Max = Convert.ToDouble(row.GetCell(7).ToString());
                        }
                        if (row.GetCell(8) != null && row.GetCell(8).ToString().Trim().Length > 0)
                        {
                            commodity.Min = Convert.ToDouble(row.GetCell(8).ToString());
                        }
                        if (row.GetCell(9) != null && row.GetCell(9).ToString().Trim().Length > 0)
                        {
                            commodity.CusId = row.GetCell(9).ToString();
                        }
                        if (row.GetCell(10) != null && row.GetCell(10).ToString().Trim().Length > 0)
                        {
                            commodity.SupId = row.GetCell(10).ToString();
                        }
                        if (row.GetCell(11) != null && row.GetCell(11).ToString().Trim().Length > 0)
                        {
                            commodity.StorId = row.GetCell(11).ToString();
                        }
                        if (row.GetCell(12) != null && row.GetCell(12).ToString().Trim().Length > 0)
                        {
                            commodity.Price = Convert.ToDouble(row.GetCell(12).ToString());
                        }
                        Data.Add(commodity);
                    }
                    var listMaterialTypeCodes = Data.Select(s => s.MaterialTypeId).Select(s => s.Trim()).Distinct().ToList();
                    var dicMaterialType = _pB_MaterialBus.GetQueryable<PB_MaterialType>().Where(w => listMaterialTypeCodes.Contains(w.Code)).ToDictionary(k => k.Code, v => v.Id);

                    var listMeasureCodes = Data.Select(s => s.MeasureId).Select(s => s.Trim()).Distinct().ToList();
                    var dicMeasure = _pB_MaterialBus.GetQueryable<PB_Measure>().Where(w => listMeasureCodes.Contains(w.Code)).ToDictionary(k => k.Code, v => v.Id);

                    var listCusCodes = Data.Select(s => s.CusId).Distinct().ToList();
                    var dicCus = _pB_MaterialBus.GetQueryable<PB_Customer>().Where(w => listCusCodes.Contains(w.Code)).ToDictionary(k => k.Code, v => v.Id);

                    var listSupCodes = Data.Select(s => s.SupId).Distinct().ToList();
                    var dicSup = _pB_MaterialBus.GetQueryable<PB_Supplier>().Where(w => listSupCodes.Contains(w.Code)).ToDictionary(k => k.Code, v => v.Id);

                    var listStorCodes = Data.Select(s => s.StorId).Select(s => s.Trim()).Distinct().ToList();
                    var dicStor = _pB_MaterialBus.GetQueryable<PB_Storage>().Where(w => listStorCodes.Contains(w.Code)).ToDictionary(k => k.Code, v => v.Id);

                    foreach (var item in Data)
                    {
                        if (dicMaterialType.ContainsKey(item.MaterialTypeId.Trim()))
                            item.MaterialTypeId = dicMaterialType[item.MaterialTypeId.Trim()];
                        else
                            throw new Exception("物料类型编号不存在!");

                        if (dicMeasure.ContainsKey(item.MeasureId.Trim()))
                            item.MeasureId = dicMeasure[item.MeasureId.Trim()];
                        else
                            throw new Exception("单位编号不存在!");

                        if (item.CusId == null)
                        {
                            item.CusId = null;
                        } else if (dicCus.ContainsKey(item.CusId.Trim()))
                            item.CusId = dicCus[item.CusId.Trim()];
                        else
                            throw new Exception("客户编号不存在!");

                        if (item.SupId == null)
                        {
                            item.SupId = null;
                        }
                        else if (dicSup.ContainsKey(item.SupId.Trim()))
                            item.SupId = dicSup[item.SupId.Trim()];
                        else
                            throw new Exception("供应商编号不存在!");

                        if (dicStor.ContainsKey(item.StorId.Trim()))
                            item.StorId = dicStor[item.StorId.Trim()];
                        else
                            throw new Exception("仓库编号不存在!");

                        if (item.BarCode == null)
                        {
                            item.BarCode = null;
                        }
                        if (item.SimpleName == null)
                        {
                            item.SimpleName = null;
                        }
                        if (item.Spec == null)
                        {
                            item.Spec = null;
                        }
                        if (item.Max == null)
                        {
                            item.Max = null;
                        }
                        if (item.Min == null)
                        {
                            item.Min = null;
                        }
                        if (item.Price == null)
                        {
                            item.Price = null;
                        }

                    }
                    if (Data.Count > 0)
                    {
                        int j = 1000;
                        for (int i = 0; i < Data.Count; i += 1000)
                        {
                            var cList = new List<PB_Material>();
                            cList = Data.Take(j).Skip(i).ToList();
                            j += 1000;
                            await _pB_MaterialBus.AddDataExlAsync(cList);
                        }
                        ReturnValue = $"数据导入成功,共导入{CountRow - 1}条数据。";
                    }
                }
                if (!flag)
                {
                    return Error(ReturnValue = "数据存在问题!" + ReturnValue);
                }
            }
            catch (Exception)
            {
                return Error("数据异常!");
            }

            return Success(ReturnValue);

        }

19 Source : Light.cs
with GNU Lesser General Public License v2.1
from axiom3d

protected override MovableObject _createInstance(string name, NamedParameterList param)
        {
            var light = new Light(name);

            if (param != null)
            {
                // Setting the light type first before any property specific to a certain light type
                if (param.ContainsKey("type"))
                {
                    switch (param["type"].ToString())
                    {
                        case "point":
                            light.Type = LightType.Point;
                            break;
                        case "directional":
                            light.Type = LightType.Directional;
                            break;
                        case "spot":
                        case "spotlight":
                            light.Type = LightType.Spotlight;
                            break;
                        default:
                            throw new AxiomException("Invalid light type '" + param["type"] + "'.");
                    }
                }

                // Common properties
                if (param.ContainsKey("position"))
                {
                    light.Position = Vector3.Parse(param["position"].ToString());
                }

                if (param.ContainsKey("direction"))
                {
                    light.Direction = Vector3.Parse(param["direction"].ToString());
                }

                if (param.ContainsKey("diffuseColour"))
                {
                    light.Diffuse = ColorEx.Parse_0_255_String(param["diffuseColour"].ToString());
                }

                if (param.ContainsKey("specularColour"))
                {
                    light.Specular = ColorEx.Parse_0_255_String(param["specularColour"].ToString());
                }

                if (param.ContainsKey("attenuation"))
                {
                    var attenuation = Vector4.Parse(param["attenuation"].ToString());
                    light.SetAttenuation(attenuation.x, attenuation.y, attenuation.z, attenuation.w);
                }

                if (param.ContainsKey("castShadows"))
                {
                    light.CastShadows = Convert.ToBoolean(param["castShadows"].ToString());
                }

                if (param.ContainsKey("visible"))
                {
                    light.CastShadows = Convert.ToBoolean(param["visible"].ToString());
                }
                // TODO: Add PowerScale Property to Light
                if (param.ContainsKey("powerScale"))
                {
                    light.PowerScale = (float)Convert.ToDouble(param["powerScale"].ToString());
                }
                // TODO: Add ShadowFarDistance to Light
                if (param.ContainsKey("shadowFarDistance"))
                {
                    light.ShadowFarDistance = (float)Convert.ToDouble(param["shadowFarDistance"].ToString());
                }

                // Spotlight properties
                if (param.ContainsKey("spotlightInner"))
                {
                    light.SpotlightInnerAngle = (float)Convert.ToDouble(param["spotlightInner"].ToString());
                }

                if (param.ContainsKey("spotlightOuter"))
                {
                    light.SpotlightOuterAngle = (float)Convert.ToDouble(param["spotlightOuter"].ToString());
                }

                if (param.ContainsKey("spotlightFalloff"))
                {
                    light.SpotlightFalloff = (float)Convert.ToDouble(param["spotlightFalloff"].ToString());
                }
            }

            return light;
        }

19 Source : NewtonsoftInteropTests.cs
with MIT License
from Azure

public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
            {
                if (reader.TokenType != Newtonsoft.Json.JsonToken.Integer && reader.TokenType != Newtonsoft.Json.JsonToken.Float)
                {
                    throw new Exception(RMResources.DateTimeConverterInvalidReaderValue);
                }

                double totalSeconds;
                try
                {
                    totalSeconds = Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture);
                }
                catch
                {
                    throw new Exception(RMResources.DateTimeConveterInvalidReaderDoubleValue);
                }

                return UnixStartTime.AddSeconds(totalSeconds);
            }

19 Source : UnixDateTimeConverter.cs
with MIT License
from Azure

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType != Newtonsoft.Json.JsonToken.Integer)
            {
                throw new Exception("Invalid value; expected integer.");
            }

            double totalSeconds;

            try
            {
                totalSeconds = Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture);
            }
            catch
            {
                throw new Exception("Invalid data; expected double");
            }

            return UnixStartTime.AddSeconds(totalSeconds);
        }

19 Source : CosmosItemUnitTests.cs
with MIT License
from Azure

[TestMethod]
        public async Task TestGetParreplacedionKeyValueFromStreamAsync()
        {
            ContainerInternal mockContainer = (ContainerInternal)MockCosmosUtil.CreateMockCosmosClient().GetContainer("TestDb", "Test");
            Mock<ContainerInternal> containerMock = new Mock<ContainerInternal>();
            ContainerInternal container = containerMock.Object;

            containerMock.Setup(e => e.GetParreplacedionKeyPathTokensAsync(It.IsAny<ITrace>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult((IReadOnlyList<IReadOnlyList<string>>)new List<IReadOnlyList<string>> { new List<string> { "pk" } }));
            containerMock
                .Setup(
                    x => x.GetParreplacedionKeyValueFromStreamAsync(
                        It.IsAny<Stream>(), 
                        It.IsAny<ITrace>(), 
                        It.IsAny<CancellationToken>()))
                .Returns<Stream, ITrace, CancellationToken>(
                (stream, trace, cancellationToken) => mockContainer.GetParreplacedionKeyValueFromStreamAsync(
                    stream,
                    trace, 
                    cancellationToken));

            DateTime dateTime = new DateTime(2019, 05, 15, 12, 1, 2, 3, DateTimeKind.Utc);
            Guid guid = Guid.NewGuid();

            //Test supported types
            List<dynamic> supportedTypesToTest = new List<dynamic> {
                new { pk = true },
                new { pk = false },
                new { pk = byte.MaxValue },
                new { pk = sbyte.MaxValue },
                new { pk = short.MaxValue },
                new { pk = ushort.MaxValue },
                new { pk = int.MaxValue },
                new { pk = uint.MaxValue },
                new { pk = long.MaxValue },
                new { pk = ulong.MaxValue },
                new { pk = float.MaxValue },
                new { pk = double.MaxValue },
                new { pk = decimal.MaxValue },
                new { pk = char.MaxValue },
                new { pk = "test" },
                new { pk = dateTime },
                new { pk = guid },
            };

            foreach (dynamic poco in supportedTypesToTest)
            {
                object pk = await container.GetParreplacedionKeyValueFromStreamAsync(
                    MockCosmosUtil.Serializer.ToStream(poco),
                    NoOpTrace.Singleton,
                    default(CancellationToken));
                if (pk is bool boolValue)
                {
                    replacedert.AreEqual(poco.pk, boolValue);
                }
                else if (pk is double doubleValue)
                {
                    if (poco.pk is float)
                    {
                        replacedert.AreEqual(poco.pk, Convert.ToSingle(pk));
                    }
                    else if (poco.pk is double)
                    {
                        replacedert.AreEqual(poco.pk, Convert.ToDouble(pk));
                    }
                    else if (poco.pk is decimal)
                    {
                        replacedert.AreEqual(Convert.ToDouble(poco.pk), (double)pk);
                    }
                }
                else if (pk is string stringValue)
                {
                    if (poco.pk is DateTime)
                    {
                        replacedert.AreEqual(poco.pk.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"), stringValue);
                    }
                    else
                    {
                        replacedert.AreEqual(poco.pk.ToString(), (string)pk);
                    }
                }
            }

            //Unsupported types should throw
            List<dynamic> unsupportedTypesToTest = new List<dynamic> {
                new { pk = new { test = "test" } },
                new { pk = new int[]{ 1, 2, 3 } },
                new { pk = new ArraySegment<byte>(new byte[]{ 0 }) },
            };

            foreach (dynamic poco in unsupportedTypesToTest)
            {
                await replacedert.ThrowsExceptionAsync<ArgumentException>(async () => await container.GetParreplacedionKeyValueFromStreamAsync(
                    MockCosmosUtil.Serializer.ToStream(poco),
                    NoOpTrace.Singleton,
                    default(CancellationToken)));
            }

            //null should return null
            object pkValue = await container.GetParreplacedionKeyValueFromStreamAsync(
                MockCosmosUtil.Serializer.ToStream(new { pk = (object)null }),
                NoOpTrace.Singleton,
                default);
            replacedert.AreEqual(Cosmos.ParreplacedionKey.Null, pkValue);
        }

19 Source : TypeVisitor.cs
with MIT License
from Azure

protected IOpenApiAny GetOpenApiPropertyDefault(OpenApiPropertyAttribute attr)
        {
            var @default = attr.Default;
            if (@default.IsNullOrDefault())
            {
                return null;
            }

            if (@default is bool)
            {
                return new OpenApiBoolean((bool) @default);
            }

            if (@default is DateTime)
            {
                return new OpenApiDateTime((DateTime) @default);
            }

            if (@default is DateTimeOffset)
            {
                return new OpenApiDateTime((DateTimeOffset) @default);
            }

            if (@default is float)
            {
                return new OpenApiFloat((float) @default);
            }

            if (@default is double)
            {
                return new OpenApiDouble((double) @default);
            }

            if (@default is decimal)
            {
                return new OpenApiDouble(Convert.ToDouble(@default));
            }

            if (@default is byte[])
            {
                return new OpenApiByte((byte[]) @default);
            }

            if (@default is short)
            {
                return new OpenApiInteger((short) @default);
            }

            if (@default is int)
            {
                return new OpenApiInteger((int) @default);
            }

            if (@default is long)
            {
                return new OpenApiLong((long) @default);
            }

            if (@default is ushort)
            {
                return new OpenApiInteger(Convert.ToInt16(@default));
            }

            if (@default is uint)
            {
                return new OpenApiInteger(Convert.ToInt32(@default));
            }

            if (@default is ulong)
            {
                return new OpenApiLong(Convert.ToInt64(@default));
            }

            if (@default is Guid)
            {
                return new OpenApiString(Convert.ToString(@default));
            }

            return new OpenApiString((string) @default);
        }

19 Source : DecimalTypeVisitorTests.cs
with MIT License
from Azure

[DataTestMethod]
        [DataRow("hello", true, "lorem ipsum")]
        [DataRow("hello", false, "lorem ipsum")]
        public void Given_OpenApiPropertyAttribute_With_Default_When_Visit_Invoked_Then_It_Should_Return_Result(string name, bool nullable, string description)
        {
            var @default = 1.0M;
            var acceptor = new OpenApiSchemaAcceptor();
            var type = new KeyValuePair<string, Type>(name, typeof(decimal));
            var attribute = new OpenApiPropertyAttribute() { Nullable = nullable, Default = @default, Description = description };

            this._visitor.Visit(acceptor, type, this._strategy, attribute);

            acceptor.Schemas[name].Nullable.Should().Be(nullable);
            acceptor.Schemas[name].Default.Should().NotBeNull();
            (acceptor.Schemas[name].Default as OpenApiDouble).Value.Should().Be(Convert.ToDouble(@default));
            acceptor.Schemas[name].Description.Should().Be(description);
        }

19 Source : OpenApiExampleFactory.cs
with MIT License
from Azure

public static IOpenApiAny CreateInstance<T>(T instance, JsonSerializerSettings settings)
        {
            Type type = typeof(T);
            var @enum = Type.GetTypeCode(type);
            var openApiExampleValue = default(IOpenApiAny);

            switch (@enum)
            {
                case TypeCode.Int16:
                    openApiExampleValue = new OpenApiInteger(Convert.ToInt16(instance));
                    break;
                case TypeCode.Int32:
                    openApiExampleValue = new OpenApiInteger(Convert.ToInt32(instance));
                    break;
                case TypeCode.Int64:
                    openApiExampleValue = new OpenApiLong(Convert.ToInt64(instance));
                    break;
                case TypeCode.UInt16:
                    openApiExampleValue = new OpenApiDouble(Convert.ToUInt16(instance));
                    break;
                case TypeCode.UInt32:
                    openApiExampleValue = new OpenApiDouble(Convert.ToUInt32(instance));
                    break;
                case TypeCode.UInt64:
                    openApiExampleValue = new OpenApiDouble(Convert.ToUInt64(instance));
                    break;
                case TypeCode.Single:
                    openApiExampleValue = new OpenApiFloat(Convert.ToSingle(instance));
                    break;
                case TypeCode.Double:
                    openApiExampleValue = new OpenApiDouble(Convert.ToDouble(instance));
                    break;
                case TypeCode.Boolean:
                    openApiExampleValue = new OpenApiBoolean(Convert.ToBoolean(instance));
                    break;
                case TypeCode.String:
                    openApiExampleValue = new OpenApiString(Convert.ToString(instance));
                    break;
                case TypeCode.DateTime:
                    openApiExampleValue = new OpenApiDateTime(Convert.ToDateTime(instance));
                    break;
                case TypeCode.Object when type == typeof(DateTimeOffset):
                    openApiExampleValue = new OpenApiDateTime((DateTimeOffset)(Convert.ChangeType(instance, type)));
                    break;
                case TypeCode.Object when type == typeof(Guid):
                    openApiExampleValue = new OpenApiString(Convert.ToString(instance));
                    break;
                case TypeCode.Object when type == typeof(byte[]):
                    openApiExampleValue = new OpenApiString(Convert.ToBase64String((byte[])Convert.ChangeType(instance, type)));
                    break;
                case TypeCode.Object:
                    openApiExampleValue = new OpenApiString(JsonConvert.SerializeObject(instance, settings));
                    break;
                default:
                    throw new InvalidOperationException("Invalid OpenAPI data Format");
            }

            return openApiExampleValue;
        }

19 Source : InternalInterpreter.cs
with MIT License
from Azure

private void RunDecreasingScript(object scriptParams, ISmartDictionary state)
        {
            var sensors = this.JsonParamAsDictionary(scriptParams);
            foreach (var sensor in sensors)
            {
                // Extract scripts parameters from the device model script configuration
                (double min, double max, double step) = this.GetMinMaxStepParameters(sensor.Value);

                // Add the sensor to the state if missing
                if (!state.Has(sensor.Key))
                {
                    state.Set(sensor.Key, max, false);
                }

                double current = Convert.ToDouble(state.Get(sensor.Key));
                double next = AreEqual(current, min) ? max : Math.Max(current - step, min);

                state.Set(sensor.Key, next, false);
            }
        }

19 Source : InternalInterpreter.cs
with MIT License
from Azure

private (double, double) GetMinMaxParameters(object parameters)
        {
            var dict = this.JsonParamAsDictionary(parameters);

            if (!dict.ContainsKey("Min"))
            {
                this.log.Error("Missing 'Min' parameter", () => new { dict });
                throw new FormatException("Missing 'Min' parameter");
            }

            if (!dict.ContainsKey("Max"))
            {
                this.log.Error("Missing 'Max' parameter", () => new { dict });
                throw new FormatException("Missing 'Max' parameter");
            }

            return (Convert.ToDouble(dict["Min"]), Convert.ToDouble(dict["Max"]));
        }

19 Source : InternalInterpreter.cs
with MIT License
from Azure

private (double, double, double) GetMinMaxStepParameters(object parameters)
        {
            var dict = this.JsonParamAsDictionary(parameters);

            if (!dict.ContainsKey("Min"))
            {
                this.log.Error("Missing 'Min' parameter", () => new { dict });
                throw new FormatException("Missing 'Min' parameter");
            }

            if (!dict.ContainsKey("Max"))
            {
                this.log.Error("Missing 'Max' parameter", () => new { dict });
                throw new FormatException("Missing 'Max' parameter");
            }

            if (!dict.ContainsKey("Step"))
            {
                this.log.Error("Missing 'Step' parameter", () => new { dict });
                throw new FormatException("Missing 'Step' parameter");
            }

            return (Convert.ToDouble(dict["Min"]),
                Convert.ToDouble(dict["Max"]),
                Convert.ToDouble(dict["Step"]));
        }

19 Source : InternalInterpreter.cs
with MIT License
from Azure

private void RunIncreasingScript(object scriptParams, ISmartDictionary state)
        {
            var sensors = this.JsonParamAsDictionary(scriptParams);
            foreach (var sensor in sensors)
            {
                // Extract scripts parameters from the device model script configuration
                (double min, double max, double step) = this.GetMinMaxStepParameters(sensor.Value);

                // Add the sensor to the state if missing
                if (!state.Has(sensor.Key))
                {
                    state.Set(sensor.Key, min, false);
                }

                double current = Convert.ToDouble(state.Get(sensor.Key));
                double next = AreEqual(current, max) ? min : Math.Min(current + step, max);

                state.Set(sensor.Key, next, false);
            }
        }

19 Source : AirTrafficListener.cs
with MIT License
from Azure

private void GeneratePlaneStatus(byte[] bytes)
        {
            if (bytes == null) return;

            statusInfo.Clear();

            try
            {
                var payload = Encoding.UTF8.GetString(bytes);

                foreach (var info in payload.Split("\r\n".ToCharArray(),
                    StringSplitOptions.RemoveEmptyEntries))
                {
                    var status = JsonConvert.DeserializeObject<PlaneStatusInfo>(info);

                    statusInfo.Add(new PlaneStatusInformation()
                    {
                        Plane1 = status.plane1,
                        Plane2 = status.plane2,
                        Distance = Convert.ToDouble(status.distance),
                    });
                }
            }
            catch { }
        }

19 Source : CoreConverters.cs
with MIT License
from Azure

public object Convert(object value, Type targetType, object parameter, string language)
        {
            double distance = System.Convert.ToDouble(value);

            return (Math.Abs(distance) == 0.0) ? "--" : $"{System.Convert.ToDouble(value):N0} miles";
        }

19 Source : CoreConverters.cs
with MIT License
from Azure

public object Convert(object value, Type targetType, object parameter, string language)
        {
            double speed = System.Convert.ToDouble(value);

            return (Math.Abs(speed) == 0.0) ? "--" : $"{speed:N0} mph";
        }

See More Examples