System.DateTime.CompareTo(System.DateTime)

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

297 Examples 7

19 Source : NpcCommandHandler.cs
with GNU Lesser General Public License v3.0
from 8720826

private bool CheckField(PlayerEnreplacedy player, string field, string strValue, string strRelation)
        {
            try
            {
                var relations = GetRelations(strRelation);// 1 大于,0 等于 ,-1 小于

                var fieldProp = GetFieldPropertyInfo(player, field);
                if (fieldProp == null)
                {
                    return false;
                }

                var objectValue = fieldProp.GetValue(player);
                var typeCode = Type.GetTypeCode(fieldProp.GetType());
                switch (typeCode)
                {
                    case TypeCode.Int32:
                        return relations.Contains(Convert.ToInt32(strValue).CompareTo(Convert.ToInt32(objectValue)));

                    case TypeCode.Int64:
                        return relations.Contains(Convert.ToInt64(strValue).CompareTo(Convert.ToInt64(objectValue)));

                    case TypeCode.Decimal:
                        return relations.Contains(Convert.ToDecimal(strValue).CompareTo(Convert.ToDecimal(objectValue)));

                    case TypeCode.Double:
                        return relations.Contains(Convert.ToDouble(strValue).CompareTo(Convert.ToDouble(objectValue)));

                    case TypeCode.Boolean:
                        return relations.Contains(Convert.ToBoolean(strValue).CompareTo(Convert.ToBoolean(objectValue)));

                    case TypeCode.DateTime:
                        return relations.Contains(Convert.ToDateTime(strValue).CompareTo(Convert.ToDateTime(objectValue)));

                    case TypeCode.String:
                        return relations.Contains(strValue.CompareTo(objectValue));

                    default:
                        throw new Exception($"不支持的数据类型: {typeCode}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"CheckField Exception:{ex}");
                return false;
            }
        }

19 Source : FileCache.cs
with Apache License 2.0
from acarteas

public int CompareTo(CacheItemReference other)
            {
                int i = LastAccessTime.CompareTo(other.LastAccessTime);

                // It's possible, although rare, that two different items will have
                // the same LastAccessTime. So in that case, we need to check to see
                // if they're actually the same.
                if (i == 0)
                {
                    // second order should be length (but from smallest to largest,
                    // that way we delete smaller files first)
                    i = -1 * Length.CompareTo(other.Length);
                    if (i == 0)
                    {
                        i = string.Compare(Region, other.Region);
                        if (i == 0)
                        {
                            i = Key.CompareTo(other.Key);
                        }
                    }
                }

                return i;
            }

19 Source : PlayerHouse.cs
with GNU Affero General Public License v3.0
from ACEmulator

public int CompareTo(PlayerHouse playerHouse)
        {
            var result = RentDue.CompareTo(playerHouse.RentDue);

            if (result == 0)
                result = House.Guid.Full.CompareTo(playerHouse.House.Guid.Full);

            return result;
        }

19 Source : ArrayList.cs
with Mozilla Public License 2.0
from ahyahy

public int Compare(object x, object y)
        {
            x2 = OneScriptForms.DefineTypeIValue(x);
            y2 = OneScriptForms.DefineTypeIValue(y);
            int num = 0;
            if (sortType == 3)//Boolean
            {
                if ((x2.GetType() != typeof(System.Boolean)) && (y2.GetType() != typeof(System.Boolean)))
                {
                    num = 0;
                }
                else if ((x2.GetType() != typeof(System.Boolean)) && (y2.GetType() == typeof(System.Boolean)))
                {
                    num = 1;
                }
                else if ((x2.GetType() == typeof(System.Boolean)) && (y2.GetType() != typeof(System.Boolean)))
                {
                    num = -1;
                }
                else
                {
                    num = ((System.Boolean)x2).CompareTo((System.Boolean)y2);
                    if (sortOrder == 0)
                    {
                        num = 0;
                    }
                    else if (sortOrder == 1)
                    {
                        
                    }
                    else if (sortOrder == 2)
                    {
                        num = -num;
                    }
                }
            }
            if (sortType == 2)//DateTime
            {
                if ((x2.GetType() != typeof(System.DateTime)) && (y2.GetType() != typeof(System.DateTime)))
                {
                    num = 0;
                }
                else if ((x2.GetType() != typeof(System.DateTime)) && (y2.GetType() == typeof(System.DateTime)))
                {
                    num = 1;
                }
                else if ((x2.GetType() == typeof(System.DateTime)) && (y2.GetType() != typeof(System.DateTime)))
                {
                    num = -1;
                }
                else
                {
                    num = ((System.DateTime)x2).CompareTo((System.DateTime)y2);
                    if (sortOrder == 0)
                    {
                        num = 0;
                    }
                    else if (sortOrder == 1)
                    {

                    }
                    else if (sortOrder == 2)
                    {
                        num = -num;
                    }
                }
            }
            else if (sortType == 1)//Number
            {
                if ((x2.GetType() != typeof(System.Decimal)) && (y2.GetType() != typeof(System.Decimal)))
                {
                    num = 0;
                }
                else if ((x2.GetType() != typeof(System.Decimal)) && (y2.GetType() == typeof(System.Decimal)))
                {
                    num = 1;
                }
                else if ((x2.GetType() == typeof(System.Decimal)) && (y2.GetType() != typeof(System.Decimal)))
                {
                    num = -1;
                }
                else
                {
                    num = ((System.Decimal)x2).CompareTo((System.Decimal)y2);
                    if (sortOrder == 0)
                    {
                        num = 0;
                    }
                    else if (sortOrder == 1)
                    {

                    }
                    else if (sortOrder == 2)
                    {
                        num = -num;
                    }
                }
            }
            else if (sortType == 0)// text
            {
                if ((x2.GetType() != typeof(System.String)) && (y2.GetType() != typeof(System.String)))
                {
                    num = 0;
                }
                else if ((x2.GetType() != typeof(System.String)) && (y2.GetType() == typeof(System.String)))
                {
                    num = 1;
                }
                else if ((x2.GetType() == typeof(System.String)) && (y2.GetType() != typeof(System.String)))
                {
                    num = -1;
                }
                else
                {
                    num = ((System.String)x2).CompareTo((System.String)y2);
                    if (sortOrder == 0)
                    {
                        num = 0;
                    }
                    else if (sortOrder == 1)
                    {

                    }
                    else if (sortOrder == 2)
                    {
                        num = -num;
                    }
                }
            }
            return num;
        }

19 Source : JValue.cs
with MIT License
from akaskela

internal static int Compare(JTokenType valueType, object objA, object objB)
        {
            if (objA == null && objB == null)
            {
                return 0;
            }
            if (objA != null && objB == null)
            {
                return 1;
            }
            if (objA == null && objB != null)
            {
                return -1;
            }

            switch (valueType)
            {
                case JTokenType.Integer:
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
                    if (objA is BigInteger)
                    {
                        return CompareBigInteger((BigInteger)objA, objB);
                    }
                    if (objB is BigInteger)
                    {
                        return -CompareBigInteger((BigInteger)objB, objA);
                    }
#endif
                    if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
                    {
                        return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
                    }
                    else if (objA is float || objB is float || objA is double || objB is double)
                    {
                        return CompareFloat(objA, objB);
                    }
                    else
                    {
                        return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture));
                    }
                case JTokenType.Float:
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
                    if (objA is BigInteger)
                    {
                        return CompareBigInteger((BigInteger)objA, objB);
                    }
                    if (objB is BigInteger)
                    {
                        return -CompareBigInteger((BigInteger)objB, objA);
                    }
#endif
                    return CompareFloat(objA, objB);
                case JTokenType.Comment:
                case JTokenType.String:
                case JTokenType.Raw:
                    string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture);
                    string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture);

                    return string.CompareOrdinal(s1, s2);
                case JTokenType.Boolean:
                    bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture);
                    bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture);

                    return b1.CompareTo(b2);
                case JTokenType.Date:
#if !NET20
                    if (objA is DateTime)
                    {
#endif
                        DateTime date1 = (DateTime)objA;
                        DateTime date2;

#if !NET20
                        if (objB is DateTimeOffset)
                        {
                            date2 = ((DateTimeOffset)objB).DateTime;
                        }
                        else
#endif
                        {
                            date2 = Convert.ToDateTime(objB, CultureInfo.InvariantCulture);
                        }

                        return date1.CompareTo(date2);
#if !NET20
                    }
                    else
                    {
                        DateTimeOffset date1 = (DateTimeOffset)objA;
                        DateTimeOffset date2;

                        if (objB is DateTimeOffset)
                        {
                            date2 = (DateTimeOffset)objB;
                        }
                        else
                        {
                            date2 = new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture));
                        }

                        return date1.CompareTo(date2);
                    }
#endif
                case JTokenType.Bytes:
                    if (!(objB is byte[]))
                    {
                        throw new ArgumentException("Object must be of type byte[].");
                    }

                    byte[] bytes1 = objA as byte[];
                    byte[] bytes2 = objB as byte[];
                    if (bytes1 == null)
                    {
                        return -1;
                    }
                    if (bytes2 == null)
                    {
                        return 1;
                    }

                    return MiscellaneousUtils.ByteArrayCompare(bytes1, bytes2);
                case JTokenType.Guid:
                    if (!(objB is Guid))
                    {
                        throw new ArgumentException("Object must be of type Guid.");
                    }

                    Guid guid1 = (Guid)objA;
                    Guid guid2 = (Guid)objB;

                    return guid1.CompareTo(guid2);
                case JTokenType.Uri:
                    if (!(objB is Uri))
                    {
                        throw new ArgumentException("Object must be of type Uri.");
                    }

                    Uri uri1 = (Uri)objA;
                    Uri uri2 = (Uri)objB;

                    return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString());
                case JTokenType.TimeSpan:
                    if (!(objB is TimeSpan))
                    {
                        throw new ArgumentException("Object must be of type TimeSpan.");
                    }

                    TimeSpan ts1 = (TimeSpan)objA;
                    TimeSpan ts2 = (TimeSpan)objB;

                    return ts1.CompareTo(ts2);
                default:
                    throw MiscellaneousUtils.CreateArgumentOutOfRangeException("valueType", valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
            }
        }

19 Source : DateTime2ndExtension.cs
with MIT License
from AlphaYu

public static bool InRange(this DateTime @this, DateTime minValue, DateTime maxValue)
        {
            return @this.CompareTo(minValue) >= 0 && @this.CompareTo(maxValue) <= 0;
        }

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

protected virtual int CompareStringToObject(string o1, object o2)
        {
            double d1;
            if (double.TryParse(o1, out d1))
            {
                return d1.CompareTo(Convert.ToDouble(o2));
            }
            bool b1;
            if (bool.TryParse(o1, out b1))
            {
                return b1.CompareTo(Convert.ToBoolean(o2));
            }
            DateTime dt1;
            if (DateTime.TryParse(o1, out dt1))
            {
                return dt1.CompareTo(Convert.ToDateTime(o2));
            }
            return IncompatibleOperands;
        }

19 Source : FiltersFragment.cs
with Apache License 2.0
from AppRopio

protected virtual void SetupDatePicker(EditText editText, Action<DateTime> onDateSelected, DateTime minDate, DateTime maxDate, Func<DateTime> currentDateFunc)
        {
            editText.Focusable = false;
            editText.FocusableInTouchMode = false; // user touches widget on phone with touch screen
            editText.Clickable = false; // user navigates with wheel and selects widget

            editText.SetOnClickListener(new AROnClickListener(() =>
            {
                var currentDate = currentDateFunc.Invoke();

                var datePickerDialog = new DatePickerDialog(Context, (sender, e) =>
                {
                    onDateSelected?.Invoke(e.Date);
                }, currentDate.Year, currentDate.Month, currentDate.Day);

                var javaMinDt = new DateTime(1970, 1, 1);

                datePickerDialog.DatePicker.DateTime = currentDate;

                if (minDate.CompareTo(javaMinDt) > 0)
                    datePickerDialog.DatePicker.MinDate = (long)(minDate - javaMinDt).TotalMilliseconds;

                if (maxDate.CompareTo(javaMinDt) > 0)
                    datePickerDialog.DatePicker.MaxDate = (long)(maxDate - javaMinDt).TotalMilliseconds;

                datePickerDialog.Show();
            }));
        }

19 Source : CodeViewerWindow.axaml.cs
with GNU Affero General Public License v3.0
from arklumpus

public async Task Initialize(string type, string autosavePath)
        {
            string guid = Path.GetFileName(autosavePath);

            string oldestFile = null;
            DateTime oldestTime = DateTime.UnixEpoch;

            foreach (string sr in Directory.GetFiles(autosavePath))
            {
                FileInfo fi = new FileInfo(sr);

                if (fi.LastWriteTime.CompareTo(oldestTime) == 1)
                {
                    oldestTime = fi.LastWriteTime;
                    oldestFile = sr;
                }
            }

            string source = File.ReadAllText(oldestFile);

            if (type != "MarkdownEditor")
            {
                string preSource = "";
                string postSource = "";

                if (type == "StringFormatter")
                {
                    preSource = "using TreeViewer;\npublic static clreplaced FormatterModule { ";
                    postSource = "}";
                }
                else if (type == "NumberFormatter")
                {
                    preSource = "using TreeViewer;\npublic static clreplaced FormatterModule {";
                    postSource = "}";
                }
                else if (type == "ColourFormatter")
                {
                    preSource = "using TreeViewer;\nusing VectSharp;\nusing System;\nusing System.Collections.Generic;\npublic static clreplaced FormatterModule {";
                    postSource = "}";
                }

                Editor editor = await Editor.Create(source, preSource, postSource, guid: guid);
                editor.Background = this.Background;
                editor.AccessType = Editor.AccessTypes.ReadOnlyWithHistoryAndErrors;

                this.FindControl<Grid>("MainContainer").Children.Add(editor);
            }
            else
            {
                this.replacedle = "Markdown viewer";

                MDEdit.Editor editor = await MDEdit.Editor.Create(source, guid);
                editor.Background = this.Background;
                editor.MarkdownRenderer.ImageUriResolver = (a, b) => MarkdownUtils.ImageUriResolverAsynchronous(a, b, null);
                editor.MarkdownRenderer.RasterImageLoader = imageFile => new VectSharp.MuPDFUtils.RasterImageFile(imageFile);
                editor.AccessType = MDEdit.Editor.AccessTypes.ReadOnlyWithHistory;

                this.FindControl<Grid>("MainContainer").Children.Add(editor);
            }
        }

19 Source : ModuleCreatorWindow.axaml.cs
with GNU Affero General Public License v3.0
from arklumpus

private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);

            if (GlobalSettings.Settings.InterfaceStyle == GlobalSettings.InterfaceStyles.MacOSStyle)
            {
                this.Clreplacedes.Add("MacOSStyle");
            }
            else if (GlobalSettings.Settings.InterfaceStyle == GlobalSettings.InterfaceStyles.WindowsStyle)
            {
                this.Clreplacedes.Add("WindowsStyle");
            }

            this.FindControl<Grid>("HeaderGrid").Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.ModuleCreator")) { Width = 32, Height = 32 });



            ((Grid)this.FindControl<Button>("FileTypeModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.FileType")) { Width = 32, Height = 32 });
            ((Grid)this.FindControl<Button>("LoadFileModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.LoadFile")) { Width = 32, Height = 32 });
            ((Grid)this.FindControl<Button>("TransformerModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.Transformer")) { Width = 32, Height = 32 });
            ((Grid)this.FindControl<Button>("FurtherTransformationModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.FurtherTransformations")) { Width = 32, Height = 32 });
            ((Grid)this.FindControl<Button>("CoordinatesModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.Coordinates")) { Width = 32, Height = 32 });
            ((Grid)this.FindControl<Button>("PlotActionModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.PlotActions")) { Width = 32, Height = 32 });
            ((Grid)this.FindControl<Button>("SelectionActionModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.SelectionAction")) { Width = 32, Height = 32 });
            ((Grid)this.FindControl<Button>("ActionModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.Action")) { Width = 32, Height = 32 });
            ((Grid)this.FindControl<Button>("MenuActionModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.MenuAction")) { Width = 32, Height = 32 });

            if (DebuggerServer == null)
            {
                DebuggerServer = Modules.GetNewDebuggerServer();
            }

            ((IControlledApplicationLifetime)Application.Current.ApplicationLifetime).Exit += (s, e) =>
            {
                DebuggerServer.Dispose();
            };

            NativeMenu menu = new NativeMenu();
            NativeMenuItem moduleMenu = new NativeMenuItem() { Header = "Edit" };

            NativeMenu moduleSubMenu = new NativeMenu();

            NativeMenuItem encodeBinaryFile = new NativeMenuItem() { Header = "Encode binary file in Base64...", Command = new SimpleCommand(win => ((ModuleCreatorWindow)win).CodeEditor != null, async a => await EncodeBinaryFileInBase64(), this, CodeEditorProperty) };
            moduleSubMenu.Add(encodeBinaryFile);

            NativeMenuItem encodeTextFile = new NativeMenuItem() { Header = "Encode text file in Base64...", Command = new SimpleCommand(win => ((ModuleCreatorWindow)win).CodeEditor != null, async a => await EncodeTextFileInBase64(), this, CodeEditorProperty) };
            moduleSubMenu.Add(encodeTextFile);

            moduleMenu.Menu = moduleSubMenu;
            menu.Add(moduleMenu);

            NativeMenu.SetMenu(this, menu);

            this.Closing += (s, e) =>
            {
                SplashScreen splash = new SplashScreen(SubsequentArgs);
                splash.OnModulesLoaded = loadAdditionalModule;

                splash.Show();
            };

            List<(string, string, int, DateTime)> recenreplacedems = new List<(string, string, int, DateTime)>();

            string autosavePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), replacedembly.GetEntryreplacedembly().GetName().Name);

            if (Directory.Exists(autosavePath))
            {
                foreach (string directory in Directory.GetDirectories(autosavePath))
                {
                    string editorId = Path.GetFileName(directory);

                    if (editorId.StartsWith("ModuleCreator"))
                    {
                        try
                        {
                            editorId = editorId.Substring(editorId.IndexOf("_") + 1);

                            string moduleType = editorId.Substring(0, editorId.IndexOf("_"));

                            DirectoryInfo info = new DirectoryInfo(directory);

                            DateTime date = info.LastWriteTime;

                            int count = info.EnumerateFiles().Count();

                            if (count > 0)
                            {
                                recenreplacedems.Add((directory, moduleType, count, date));
                            }
                        }
                        catch { }
                    }
                }

                int index = 2;

                foreach ((string, string, int, DateTime) item in recenreplacedems.OrderByDescending(a => a.Item4))
                {
                    Grid itemGrid = new Grid() { Height = 42, Width = 260, Margin = new Thickness(0, 0, 5, 5), Background = Avalonia.Media.Brushes.Transparent };
                    itemGrid.ColumnDefinitions.Add(new ColumnDefinition(37, GridUnitType.Pixel));
                    itemGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                    itemGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));

                    StackPanel namePanel = new StackPanel() { Margin = new Thickness(5, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                    Grid.SetColumn(namePanel, 1);
                    itemGrid.Children.Add(namePanel);

                    TrimmedTextBox2 nameBlock;
                    TrimmedTextBox2 dateBlock;

                    {
                        nameBlock = new TrimmedTextBox2() { Text = moduleTypeTranslations[item.Item2], FontSize = 16, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                        AvaloniaBugFixes.SetToolTip(nameBlock, new TextBlock() { Text = moduleTypeTranslations[item.Item2], TextWrapping = Avalonia.Media.TextWrapping.NoWrap });
                        namePanel.Children.Add(nameBlock);
                    }

                    {
                        dateBlock = new TrimmedTextBox2() { Text = item.Item4.ToString("f"), Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(102, 102, 102)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 12 };
                        AvaloniaBugFixes.SetToolTip(dateBlock, new TextBlock() { Text = item.Item4.ToString("f"), TextWrapping = Avalonia.Media.TextWrapping.NoWrap });
                        namePanel.Children.Add(dateBlock);
                    }

                    itemGrid.Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets." + moduleTypeIcons[item.Item2])) { Width = 32, Height = 32, Margin = new Thickness(5, 0, 0, 0), HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center });

                    StackPanel buttonsPanel = new StackPanel() { VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                    Grid.SetColumn(buttonsPanel, 2);
                    itemGrid.Children.Add(buttonsPanel);

                    Button deleteButton = new Button() { Foreground = Avalonia.Media.Brushes.Black, Content = new DPIAwareBox(Icons.GetIcon16("TreeViewer.replacedets.Trash")) { Width = 16, Height = 16 }, Background = Avalonia.Media.Brushes.Transparent, Padding = new Thickness(0), Width = 24, Height = 24, Margin = new Thickness(0, 0, 0, 2), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, IsVisible = false };
                    buttonsPanel.Children.Add(deleteButton);
                    AvaloniaBugFixes.SetToolTip(deleteButton, new TextBlock() { Text = "Delete", Foreground = Avalonia.Media.Brushes.Black });
                    deleteButton.Clreplacedes.Add("SideBarButton");

                    itemGrid.PointerEnter += (s, e) =>
                    {
                        deleteButton.IsVisible = true;
                        itemGrid.Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(210, 210, 210));
                    };

                    itemGrid.PointerLeave += (s, e) =>
                    {
                        deleteButton.IsVisible = false;
                        itemGrid.Background = Avalonia.Media.Brushes.Transparent;
                    };

                    itemGrid.PointerPressed += (s, e) =>
                    {
                        itemGrid.Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(177, 177, 177));
                    };

                    itemGrid.PointerReleased += async (s, e) =>
                    {
                        itemGrid.Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(210, 210, 210));

                        Point pos = e.GetCurrentPoint(itemGrid).Position;

                        if (pos.X >= 0 && pos.Y >= 0 && pos.X <= itemGrid.Bounds.Width && pos.Y <= itemGrid.Bounds.Height)
                        {
                            string guid = Path.GetFileName(item.Item1);

                            string oldestFile = null;
                            DateTime oldestTime = DateTime.UnixEpoch;

                            foreach (string sr in Directory.GetFiles(item.Item1))
                            {
                                FileInfo fi = new FileInfo(sr);

                                if (fi.LastWriteTime.CompareTo(oldestTime) == 1)
                                {
                                    oldestTime = fi.LastWriteTime;
                                    oldestFile = sr;
                                }
                            }

                            string moduleSource = File.ReadAllText(oldestFile);

                            await InitializeEditor(moduleSource, guid);
                        }
                    };

                    deleteButton.Click += async (s, e) =>
                    {
                        try
                        {
                            Directory.Delete(item.Item1, true);

                            this.FindControl<WrapPanel>("RecentFilesGrid").Children.Remove(itemGrid);
                        }
                        catch (Exception ex)
                        {
                            MessageBox box = new MessageBox("Attention", "An error occurred while deleting the file!\n" + ex.Message);
                            await box.ShowDialog2(this);
                        }
                    }; ;


                    this.FindControl<WrapPanel>("RecentFilesGrid").Children.Add(itemGrid);

                    index++;
                }
            }
            else
            {
                Directory.CreateDirectory(autosavePath);
            }

            this.FindControl<Button>("FileTypeModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.FileType.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_FileType_" + guid.ToString());
            };

            this.FindControl<Button>("PlotActionModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.PlotAction.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_PlotAction_" + guid.ToString());
            };

            this.FindControl<Button>("LoadFileModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.LoadFile.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_LoadFile_" + guid.ToString());
            };

            this.FindControl<Button>("TransformerModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.Transformer.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_Transformer_" + guid.ToString());
            };

            this.FindControl<Button>("FurtherTransformationModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.FurtherTransformation.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_FurtherTransformation_" + guid.ToString());
            };

            this.FindControl<Button>("CoordinatesModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.Coordinates.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_Coordinates_" + guid.ToString());
            };

            this.FindControl<Button>("SelectionActionModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.SelectionAction.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_SelectionAction_" + guid.ToString());
            };

            this.FindControl<Button>("ActionModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.Action.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_Action_" + guid.ToString());
            };

            this.FindControl<Button>("MenuActionModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.MenuAction.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_MenuAction_" + guid.ToString());
            };
        }

19 Source : DateUtil.cs
with MIT License
from ArnaudValensi

public static int CompareStringDate(string date1, string date2) {
		DateTime dateTime1 = DateUtil.StringToDateTime(date1);
		DateTime dateTime2 = DateUtil.StringToDateTime(date2);

		return dateTime1.CompareTo(dateTime2);
	}

19 Source : ScheduleEvent.cs
with GNU Affero General Public License v3.0
from asmejkal

public int CompareTo(ScheduleEvent other)
        {
            int c = 0;
            if ((c = Date.CompareTo(other.Date)) != 0)
                return c;

            if ((c = Description.CompareTo(other.Description)) != 0)
                return c;
            
            if ((c = (Tag ?? string.Empty).CompareTo(other.Tag ?? string.Empty)) != 0)
                return c;

            if ((c = (Link ?? string.Empty).CompareTo(other.Link ?? string.Empty)) != 0)
                return c;

            return Id.CompareTo(other.Id);
        }

19 Source : FormBackground.cs
with MIT License
from AutoItConsulting

private bool RefreshBackgroundImage(bool forceUpdate = false)
        {
            // Get the current user's wallpaper
            string wallpaperPath = GetCurrentUserWallpaperPath();

            // If wallpaper is blank or doesn't exist then quit as we can't do anything useful
            if (string.IsNullOrEmpty(wallpaperPath) || !File.Exists(wallpaperPath))
            {
                return false;
            }

            // Get Current filename and filetime and check if we need to update the image
            DateTime modifiedTime = File.GetLastWriteTime(wallpaperPath);
            if (!forceUpdate && _wallpaperPath == wallpaperPath && _wallpaperLastModified.CompareTo(modifiedTime) == 0)
            {
                return false;
            }

            // Save new values
            _wallpaperPath = wallpaperPath;
            _wallpaperLastModified = modifiedTime;

            // Set the form bitmap and force display to primary monitor
            StartPosition = FormStartPosition.Manual;
            Location = Screen.PrimaryScreen.Bounds.Location;

            WindowState = FormWindowState.Maximized;

            // Don't use Maximized as it goes over the task bar which can be ugly
            //Size = new Size(Screen.GetWorkingArea(this).Width, Screen.GetWorkingArea(this).Height);

            try
            {
                using (var fileStream = new FileStream(wallpaperPath, FileMode.Open, FileAccess.Read))
                {
                    pictureBoxBackground.BackgroundImage = Image.FromStream(fileStream);
                    pictureBoxBackground.Invalidate();
                }
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }

19 Source : CacheImpl.cs
with MIT License
from AvaloniaUI

public bool IsExpired()
        {
            return expirationTime.HasValue && expirationTime.Value.CompareTo(DateTime.Now) <= 0;
        }

19 Source : CognitoUserSession.cs
with Apache License 2.0
from aws

public bool IsValid()
        {
            DateTime currentTimeStamp = DateTime.UtcNow;

            return (currentTimeStamp.CompareTo(ExpirationTime) < 0);
        }

19 Source : AyFuncIO.cs
with MIT License
from ay2015

public void SortAsFileCreationTimeNi(ref FileInfo[] arrFi)
        {
            Array.Sort(arrFi, delegate(FileInfo x, FileInfo y) { return y.CreationTime.CompareTo(x.CreationTime); });
        }

19 Source : AyFuncIO.cs
with MIT License
from ay2015

public void SortAsFolderCreationTimeShun(ref DirectoryInfo[] dirs)
        {
            Array.Sort(dirs, delegate(DirectoryInfo x, DirectoryInfo y) { return x.CreationTime.CompareTo(y.CreationTime); });
        }

19 Source : AyFuncIO.cs
with MIT License
from ay2015

public void SortAsFolderCreationTimeNi(ref DirectoryInfo[] dirs)
        {
            Array.Sort(dirs, delegate(DirectoryInfo x, DirectoryInfo y) { return y.CreationTime.CompareTo(x.CreationTime); });
        }

19 Source : AyFuncIO.cs
with MIT License
from ay2015

public void SortAsFileCreationTimeShun(ref FileInfo[] arrFi)
        {
            Array.Sort(arrFi, delegate(FileInfo x, FileInfo y) { return x.CreationTime.CompareTo(y.CreationTime); });
        }

19 Source : DiagnosticsController.cs
with Apache License 2.0
from Azure-App-Service

private string[] GetCurrentDockerLogFilenames(SearchOption searchOption)
        {
            var allDockerLogFilenames = FileSystemHelpers.ListFiles(_environment.LogFilesPath, searchOption, new[] { "*" }).ToArray();
            var logSources = new Dictionary<string, DockerLogSourceMap>();

            // Get all non-rolled Docker log filenames from the LogFiles directory
            foreach (var dockerLogPath in allDockerLogFilenames)
            {
                var match = NONROLLED_DOCKER_LOG_FILENAME_REGEX.Match(Path.GetFileName(dockerLogPath));
                if (match.Success)
                {
                    // Get the timestamp and log source (machine name "_" default, easyauth, empty(Docker), etc) from the file name
                    // and find the latest one for each source
                    // Note that timestamps are YYYY_MM_DD (sortable as integers with the underscores removed)
                    DateTime date;
                    if (!DateTime.TryParse(match.Groups[1].Value.Replace("_", "/"), out date))
                    {
                        continue;
                    }
                    var source = match.Groups[2].Value;

                    if (!logSources.ContainsKey(source) || logSources[source].Timestamp.CompareTo(date) < 0)
                    {
                        logSources[source] = new DockerLogSourceMap {
                            LogSource = source,
                            Timestamp = date,
                            Paths = new List<string> { dockerLogPath }
                        };
                    }
                    else
                    {
                        logSources[source].Paths.Add(dockerLogPath);
                    }
                }
            }

            if (logSources.Keys.Count == 0)
            {
                return new string[0];
            }

            var timeStampThreshold = logSources.Values.Max(v => v.Timestamp).AddDays(-7);
            return logSources.Values.Where(v => v.Timestamp >= timeStampThreshold).SelectMany(m => m.Paths).ToArray();
        }

19 Source : HostAssignmentContext.cs
with Apache License 2.0
from Azure-App-Service

public bool Equals(HostreplacedignmentContext other)
        {
            if (other == null)
            {
                return false;
            }

            return SiteId == other.SiteId && LastModifiedTime.CompareTo(other.LastModifiedTime) == 0;
        }

19 Source : App.axaml.cs
with MIT License
from b-editor

private static void RunBackup()
        {
            BackupTimer.Tick += (s, e) =>
            {
                Task.Run(() =>
                {
                    var proj = AppModel.Current.Project;
                    if (proj is not null && Settings.Default.AutoBackUp)
                    {
                        var dir = Path.Combine(proj.DirectoryName, "backup");
                        if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);

                        proj.Save(Path.Combine(dir, DateTime.Now.ToString("HH:mm:ss").Replace(':', '_')) + ".backup");

                        var files = Directory.GetFiles(dir).Select(i => new FileInfo(i)).ToArray();
                        Array.Sort(files, (x, y) => y.LastWriteTime.CompareTo(x.LastWriteTime));
                        if (files.Length is > 10)
                        {
                            foreach (var file in files.Skip(10))
                            {
                                if (file.Exists) file.Delete();
                            }
                        }
                    }
                });
            };

19 Source : MainForm.cs
with MIT License
from baaron4

private string DiscordBatch(out List<ulong> ids)
        {
            ids = new List<ulong>();
            AddTraceMessage("Sending batch to Discord");
            if (Properties.Settings.Default.WebhookURL == null)
            {
                return "Set a discord webhook url in settings first";
            }
            var fullDpsReportLogs = new List<FormOperationController>();
            foreach (FormOperationController operation in OperatorBindingSource)
            {
                if (operation.DPSReportLink != null && operation.DPSReportLink.Contains("https"))
                {
                    fullDpsReportLogs.Add(operation);
                }
            }
            if (!fullDpsReportLogs.Any())
            {
                return "Nothing to send";
            }
            // first sort by time
            fullDpsReportLogs.Sort((x, y) =>
            {
                return DateTime.Parse(x.BasicMetaData.LogStart).CompareTo(DateTime.Parse(y.BasicMetaData.LogStart));
            });
            var fullDpsReportsLogsByDate = fullDpsReportLogs.GroupBy(x => DateTime.Parse(x.BasicMetaData.LogStart).Date).ToDictionary(x => x.Key, x => x.ToList());
            // split the logs so that a single embed does not reach the discord embed limit and also keep a reasonable size by embed
            string message = "";
            bool start = true;
            foreach (KeyValuePair<DateTime, List<FormOperationController>> pair in fullDpsReportsLogsByDate)
            {
                if (!start)
                {
                    message += "\r\n";
                }
                start = false;
                var splitDpsReportLogs = new List<List<FormOperationController>>() { new List<FormOperationController>() };
                message += pair.Key.ToString("yyyy-MM-dd") + " - ";
                List<FormOperationController> curListToFill = splitDpsReportLogs.First();
                foreach (FormOperationController controller in pair.Value)
                {
                    if (curListToFill.Count < 40)
                    {
                        curListToFill.Add(controller);
                    }
                    else
                    {
                        curListToFill = new List<FormOperationController>()
                    {
                        controller
                    };
                        splitDpsReportLogs.Add(curListToFill);
                    }
                }
                foreach (List<FormOperationController> dpsReportLogs in splitDpsReportLogs)
                {
                    EmbedBuilder embedBuilder = ProgramHelper.GetEmbedBuilder();
                    embedBuilder.WithCurrentTimestamp();
                    embedBuilder.WithFooter(pair.Key.ToString("yyyy-MM-dd"));
                    dpsReportLogs.Sort((x, y) =>
                    {
                        var categoryCompare = x.BasicMetaData.FightCategory.CompareTo(y.BasicMetaData.FightCategory);
                        if (categoryCompare == 0)
                        {
                            return DateTime.Parse(x.BasicMetaData.LogStart).CompareTo(DateTime.Parse(y.BasicMetaData.LogStart));
                        }
                        return categoryCompare;
                    });
                    string currentSubCategory = "";
                    var embedFieldBuilder = new EmbedFieldBuilder();
                    var fieldValue = "I can not be empty";
                    foreach (FormOperationController controller in dpsReportLogs)
                    {
                        string subCategory = controller.BasicMetaData.FightCategory.GetSubCategoryName();
                        string toAdd = "[" + controller.BasicMetaData.FightName + "](" + controller.DPSReportLink + ") " + (controller.BasicMetaData.FightSuccess ? " :white_check_mark: " : " :x: ") + ": " + controller.BasicMetaData.FightDuration;
                        if (subCategory != currentSubCategory)
                        {
                            embedFieldBuilder.WithValue(fieldValue);
                            embedFieldBuilder = new EmbedFieldBuilder();
                            fieldValue = "";
                            embedBuilder.AddField(embedFieldBuilder);
                            embedFieldBuilder.WithName(subCategory);
                            currentSubCategory = subCategory;
                        }
                        else if (fieldValue.Length + toAdd.Length > 1024)
                        {
                            embedFieldBuilder.WithValue(fieldValue);
                            embedFieldBuilder = new EmbedFieldBuilder();
                            fieldValue = "";
                            embedBuilder.AddField(embedFieldBuilder);
                        }
                        else
                        {
                            fieldValue += "\r\n";
                        }
                        fieldValue += toAdd;
                    }
                    embedFieldBuilder.WithValue(fieldValue);
                    ids.Add(WebhookController.SendMessage(Properties.Settings.Default.WebhookURL, embedBuilder.Build(), out string curMessage));
                    message += curMessage + " - ";
                }
            }
            return message;
        }

19 Source : PullRequestViewElement.cs
with MIT License
from bgianfo

public int CompareTo([AllowNull] PullRequestViewElement other)
        {
            // If other is null, than we must be greater.
            //
            if (other == null)
            {
                return 1;
            }

            // Force sort order descending by negating the default sort order.
            //
            return -m_updatedTime.CompareTo(other.m_updatedTime);
        }

19 Source : UDPBase.cs
with MIT License
from BlazorPlus

protected void ProcessUDPPackage(UDPPackageType pt, byte[] data)
		{
			//UDPPackageType pt = UDPMeta.GetPackageType(data);
			long sid = BitConverter.ToInt64(data, 8);

			//Console.WriteLine("ProcessUDPPackage:" + sid + ":" + pt);

			if (pt == UDPPackageType.SessionError)
			{
				Close();
			}
			else if (pt == UDPPackageType.SessionClose)
			{
				Close();
			}

			if (pt == UDPPackageType.DataPost)
			{
				if (_closed)
				{
					SendToPeer(UDPMeta.CreateSessionError(SessionId, "closed"));
					return;
				}

				long peerminreadindex = BitConverter.ToInt64(data, 16);
				lock (_postmap)
				{
					OnGetPeerMinRead(peerminreadindex);
				}

				long dataindex = BitConverter.ToInt64(data, 24);

				//Console.WriteLine("DataPost:" + dataindex);

				if (dataindex == _readminindex + 1)
				{
					OnPost(data, 32, data.Length - 32);
					_readminindex = dataindex;
					byte[] buff;
					while (_buffmap.TryGetValue(_readminindex + 1, out buff))
					{
						_readminindex++;
						_buffmap.Remove(_readminindex);
						OnPost(buff);
					}
					SendToPeer(UDPMeta.CreateDataRead(SessionId, _readminindex, dataindex));
				}
				else
				{
					if (dataindex > _readmaxindex) _readmaxindex = dataindex;
					byte[] buff = new byte[data.Length - 32];
					Buffer.BlockCopy(data, 32, buff, 0, buff.Length);
					_buffmap[dataindex] = buff;
				}

			}
			if (pt == UDPPackageType.DataRead)
			{
				long peerminreadindex = BitConverter.ToInt64(data, 16);
				long dataindex = BitConverter.ToInt64(data, 24);
				lock (_postmap)
				{
					PostMapRemove(dataindex);
					OnGetPeerMinRead(peerminreadindex);
				}
			}
			if (pt == UDPPackageType.DataMiss)
			{
				long peerminreadindex = BitConverter.ToInt64(data, 16);
				lock (_postmap)
				{
					OnGetPeerMinRead(peerminreadindex);
				}

				int misscount = (data.Length - 24) / 8;
				List<DataItem> list = null;
				for (int missid = 0; missid < misscount; missid++)
				{
					long dataindex = BitConverter.ToInt64(data, 24 + missid * 8);
					DataItem item = null;
					lock (_postmap)
					{
						_postmap.TryGetValue(dataindex, out item);
					}
					if (item != null)
					{
						if (list == null) list = new List<DataItem>();
						list.Add(item);
					}
				}
				if (list != null)
				{
					list.Sort(delegate (DataItem d1, DataItem d2)
					{
						return d1.SendTime.CompareTo(d2.SendTime);
					});
					int maxsendagain = 65536;

					foreach (DataItem item in list)
					{
						if (DateTime.Now - item.SendTime < TimeSpan.FromMilliseconds(GetPackageLostMS()))
							break;
						if (maxsendagain < item.UDPData.Length)
							break;
						maxsendagain -= item.UDPData.Length;
						UDPMeta.UpdateDataRead(item.UDPData, _readminindex);
						item.SendTime = DateTime.Now;
						item.RetryCount++;
						SendToPeer(item.UDPData);
					}
				}
			}
			if (pt == UDPPackageType.DataPing)
			{
				long peerminreadindex = BitConverter.ToInt64(data, 16);
				lock (_postmap)
				{
					OnGetPeerMinRead(peerminreadindex);
				}

				long maxdataindex = BitConverter.ToInt64(data, 24);
				List<long> misslist = null;
				for (long index = _readminindex + 1; index <= maxdataindex; index++)
				{
					if (_buffmap.ContainsKey(index))
						continue;
					if (misslist == null)
						misslist = new List<long>();
					misslist.Add(index);
					if (misslist.Count * 8 + 40 > UDPMeta.BestUDPSize)
						break;
				}
				if (misslist != null)
				{
					SendToPeer(UDPMeta.CreateDataMiss(SessionId, _readminindex, misslist.ToArray()));
				}
				else
				{
					SendToPeer(UDPMeta.CreateDataRead(SessionId, _readminindex, _readminindex));
				}
			}
		}

19 Source : ScheduledAction.cs
with GNU Affero General Public License v3.0
from blockbasenetwork

[System.Diagnostics.Codereplacedysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods",
            Justification = "NextExecutionDate.CompareTo does the job")]
        public int CompareTo(ScheduledAction other)
        {
            if (other == this) return 0;

            var diff = NextExecutionDate.CompareTo(other.NextExecutionDate);
            return (diff >= 0) ? 1 : -1;
        }

19 Source : Recognize.cs
with MIT License
from BotBuilderCommunity

public override TermMatch Parse(string input)
        {
            TermMatch match = null;

            string culture = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName ?? English;
            List<ModelResult> results = DateTimeRecognizer.RecognizeDateTime(input, culture);
            if (results.Count > 0)
            {
                List<Dictionary<string, string>> allValues = (List<Dictionary<string, string>>)results[0].Resolution["values"];
                if (allValues.Count > 0)
                {
                    // TODO: currently defaulting to the greatest date returned from DateTimeRecognizer
                    // should have constraint attributes for DateTime fields, enabling constraining the recognizer
                    DateTime? greatestDate = null;
                    foreach (var resultValue in allValues)
                    {
                        string value = null;
                        if (resultValue.TryGetValue("value", out value))
                        {
                            DateTime asDateTime;
                            if (DateTime.TryParse(value, out asDateTime))
                            {
                                if (greatestDate.HasValue)
                                {
                                    if (greatestDate.Value.CompareTo(asDateTime) < 0)
                                    {
                                        greatestDate = asDateTime;
                                    }
                                }
                                else
                                {
                                    greatestDate = asDateTime;
                                }
                            }
                        }
                    }

                    if (greatestDate.HasValue)
                    {
                        match = new TermMatch(0, input.Length, 1.0, greatestDate.Value);
                    }
                }
            }

            return match;
        }

19 Source : DateTimeAssertions.cs
with Apache License 2.0
from BoundfoxStudios

public AndConstraint<DateTimereplacedertions> BeBefore(DateTime expected, string because = "",
            params object[] becauseArgs)
        {
            Execute.replacedertion
                .ForCondition(Subject.HasValue && Subject.Value.CompareTo(expected) < 0)
                .BecauseOf(because, becauseArgs)
                .FailWith("Expected {context:the date and time} to be before {0}{reason}, but found {1}.", expected,
                    Subject ?? default(DateTime?));

            return new AndConstraint<DateTimereplacedertions>(this);
        }

19 Source : DateTimeAssertions.cs
with Apache License 2.0
from BoundfoxStudios

public AndConstraint<DateTimereplacedertions> BeOnOrBefore(DateTime expected, string because = "",
            params object[] becauseArgs)
        {
            Execute.replacedertion
                .ForCondition(Subject.HasValue && Subject.Value.CompareTo(expected) <= 0)
                .BecauseOf(because, becauseArgs)
                .FailWith("Expected {context:the date and time} to be on or before {0}{reason}, but found {1}.", expected,
                    Subject ?? default(DateTime?));

            return new AndConstraint<DateTimereplacedertions>(this);
        }

19 Source : DateTimeAssertions.cs
with Apache License 2.0
from BoundfoxStudios

public AndConstraint<DateTimereplacedertions> BeAfter(DateTime expected, string because = "",
            params object[] becauseArgs)
        {
            Execute.replacedertion
                .ForCondition(Subject.HasValue && Subject.Value.CompareTo(expected) > 0)
                .BecauseOf(because, becauseArgs)
                .FailWith("Expected {context:the date and time} to be after {0}{reason}, but found {1}.", expected,
                    Subject ?? default(DateTime?));

            return new AndConstraint<DateTimereplacedertions>(this);
        }

19 Source : DateTimeAssertions.cs
with Apache License 2.0
from BoundfoxStudios

public AndConstraint<DateTimereplacedertions> BeOnOrAfter(DateTime expected, string because = "",
            params object[] becauseArgs)
        {
            Execute.replacedertion
                .ForCondition(Subject.HasValue && Subject.Value.CompareTo(expected) >= 0)
                .BecauseOf(because, becauseArgs)
                .FailWith("Expected {context:the date and time} to be on or after {0}{reason}, but found {1}.", expected,
                    Subject ?? default(DateTime?));

            return new AndConstraint<DateTimereplacedertions>(this);
        }

19 Source : DayPeriod.cs
with Apache License 2.0
from BuffettCode

public int CompareTo(IPeriod other)
        {
            if (other is null)
            {
                throw new ArgumentNullException();
            }
            else if (this.GetType() != other.GetType())
            {
                throw new ArgumentException($"Compare to{other.GetType()} is not supported.");
            }
            else
            {
                return value.CompareTo(((DayPeriod)other).value);
            }
        }

19 Source : Car.cs
with GNU Affero General Public License v3.0
from cc004

public int CompareTo(Car other)
        {
            return other.time.CompareTo(time);
        }

19 Source : Brute.cs
with GNU General Public License v3.0
from cobbr

public static void Execute(string CovenantURI, string CovenantCertHash, string GUID, Aes SessionKey)
        {
            try
            {
                int Delay = Convert.ToInt32(@"{{REPLACE_DELAY}}");
                int Jitter = Convert.ToInt32(@"{{REPLACE_JITTER_PERCENT}}");
                int ConnectAttempts = Convert.ToInt32(@"{{REPLACE_CONNECT_ATTEMPTS}}");
                DateTime KillDate = DateTime.FromBinary(long.Parse(@"{{REPLACE_KILL_DATE}}"));
                List<string> ProfileHttpHeaderNames = @"{{REPLACE_PROFILE_HTTP_HEADER_NAMES}}".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List<string> ProfileHttpHeaderValues = @"{{REPLACE_PROFILE_HTTP_HEADER_VALUES}}".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List<string> ProfileHttpUrls = @"{{REPLACE_PROFILE_HTTP_URLS}}".Split(',').ToList().Select(U => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(U))).ToList();
                string ProfileHttpGetResponse = @"{{REPLACE_PROFILE_HTTP_GET_RESPONSE}}".Replace(Environment.NewLine, "\n");
                string ProfileHttpPostRequest = @"{{REPLACE_PROFILE_HTTP_POST_REQUEST}}".Replace(Environment.NewLine, "\n");
                string ProfileHttpPostResponse = @"{{REPLACE_PROFILE_HTTP_POST_RESPONSE}}".Replace(Environment.NewLine, "\n");
                bool ValidateCert = bool.Parse(@"{{REPLACE_VALIDATE_CERT}}");
                bool UseCertPinning = bool.Parse(@"{{REPLACE_USE_CERT_PINNING}}");

                string Hostname = Dns.GetHostName();
                string IPAddress = Dns.GetHostAddresses(Hostname)[0].ToString();
                foreach (IPAddress a in Dns.GetHostAddresses(Dns.GetHostName()))
                {
                    if (a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        IPAddress = a.ToString();
                        break;
                    }
                }
                string OperatingSystem = Environment.OSVersion.ToString();
                string Process = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
                int Integrity = 2;
                string UserDomainName = Environment.UserDomainName;
                string UserName = Environment.UserName;

                string RegisterBody = @"{ ""integrity"": " + Integrity + @", ""process"": """ + Process + @""", ""userDomainName"": """ + UserDomainName + @""", ""userName"": """ + UserName + @""", ""delay"": " + Convert.ToString(Delay) + @", ""jitter"": " + Convert.ToString(Jitter) + @", ""connectAttempts"": " + Convert.ToString(ConnectAttempts) + @", ""status"": 0, ""ipAddress"": """ + IPAddress + @""", ""hostname"": """ + Hostname + @""", ""operatingSystem"": """ + OperatingSystem + @""" }";
                IMessenger baseMessenger = null;
                baseMessenger = new HttpMessenger(CovenantURI, CovenantCertHash, UseCertPinning, ValidateCert, ProfileHttpHeaderNames, ProfileHttpHeaderValues, ProfileHttpUrls);
                baseMessenger.Read();
                baseMessenger.Identifier = GUID;
                TaskingMessenger messenger = new TaskingMessenger
                (
                    new MessageCrafter(GUID, SessionKey),
                    baseMessenger,
                    new Profile(ProfileHttpGetResponse, ProfileHttpPostRequest, ProfileHttpPostResponse)
                );
                messenger.QueueTaskingMessage(RegisterBody);
                messenger.WriteTaskingMessage();
                messenger.SetAuthenticator(messenger.ReadTaskingMessage().Message);
                try
                {
                    // A blank upward write, this helps in some cases with an HTTP Proxy
                    messenger.QueueTaskingMessage("");
                    messenger.WriteTaskingMessage();
                }
                catch (Exception) { }

                List<KeyValuePair<string, Thread>> Tasks = new List<KeyValuePair<string, Thread>>();
                Random rnd = new Random();
                int ConnectAttemptCount = 0;
                bool alive = true;
                while (alive)
                {
                    int change = rnd.Next((int)Math.Round(Delay * (Jitter / 100.00)));
                    if (rnd.Next(2) == 0) { change = -change; }
                    Thread.Sleep((Delay + change) * 1000);
                    try
                    {
                        GruntTaskingMessage message = messenger.ReadTaskingMessage();
                        if (message != null)
                        {
                            ConnectAttemptCount = 0;
                            string output = "";
                            if (message.Type == GruntTaskingType.SetDelay || message.Type == GruntTaskingType.SetJitter || message.Type == GruntTaskingType.SetConnectAttempts)
                            {
                                if (int.TryParse(message.Message, out int val))
                                {
                                    if (message.Type == GruntTaskingType.SetDelay)
                                    {
                                        Delay = val;
                                        output += "Set Delay: " + Delay;
                                    }
                                    else if (message.Type == GruntTaskingType.SetJitter)
                                    {
                                        Jitter = val;
                                        output += "Set Jitter: " + Jitter;
                                    }
                                    else if (message.Type == GruntTaskingType.SetConnectAttempts)
                                    {
                                        ConnectAttempts = val;
                                        output += "Set ConnectAttempts: " + ConnectAttempts;
                                    }
                                }
                                else
                                {
                                    output += "Error parsing: " + message.Message;
                                }
                                messenger.QueueTaskingMessage(new GruntTaskingMessageResponse(GruntTaskingStatus.Completed, output).ToJson(), message.Name);
                            }
                            else if (message.Type == GruntTaskingType.SetKillDate)
                            {
                                if (DateTime.TryParse(message.Message, out DateTime date))
                                {
                                    KillDate = date;
                                    output += "Set KillDate: " + KillDate.ToString();
                                }
                                else
                                {
                                    output += "Error parsing: " + message.Message;
                                }
                                messenger.QueueTaskingMessage(new GruntTaskingMessageResponse(GruntTaskingStatus.Completed, output).ToJson(), message.Name);
                            }
                            else if (message.Type == GruntTaskingType.Exit)
                            {
                                output += "Exited";
                                messenger.QueueTaskingMessage(new GruntTaskingMessageResponse(GruntTaskingStatus.Completed, output).ToJson(), message.Name);
                                messenger.WriteTaskingMessage();
                                return;
                            }
                            else if(message.Type == GruntTaskingType.Tasks)
                            {
                                if (!Tasks.Where(T => T.Value.ThreadState == ThreadState.Running).Any()) { output += "No active tasks!"; }
                                else
                                {
                                    output += "Task       Status" + Environment.NewLine;
                                    output += "----       ------" + Environment.NewLine;
                                    output += String.Join(Environment.NewLine, Tasks.Where(T => T.Value.ThreadState == ThreadState.Running).Select(T => T.Key + " Active").ToArray());
                                }
                                messenger.QueueTaskingMessage(new GruntTaskingMessageResponse(GruntTaskingStatus.Completed, output).ToJson(), message.Name);
                            }
                            else if(message.Type == GruntTaskingType.TaskKill)
                            {
                                var matched = Tasks.Where(T => T.Value.ThreadState == ThreadState.Running && T.Key.ToLower() == message.Message.ToLower());
                                if (!matched.Any())
                                {
                                    output += "No active task with name: " + message.Message;
                                }
                                else
                                {
                                    KeyValuePair<string, Thread> t = matched.First();
                                    t.Value.Abort();
                                    Thread.Sleep(3000);
                                    if (t.Value.IsAlive)
                                    {
                                        t.Value.Suspend();
                                    }
                                    output += "Task: " + t.Key + " killed!";
                                }
                                messenger.QueueTaskingMessage(new GruntTaskingMessageResponse(GruntTaskingStatus.Completed, output).ToJson(), message.Name);
                            }
                            else if (message.Token)
                            {
                                Thread t = new Thread(() => TaskExecute(messenger, message, Delay));
                                t.Start();
                                Tasks.Add(new KeyValuePair<string, Thread>(message.Name, t));
                                bool completed = t.Join(5000);
                            }
                            else
                            {
                                Thread t = new Thread(() => TaskExecute(messenger, message, Delay));
                                t.Start();
                                Tasks.Add(new KeyValuePair<string, Thread>(message.Name, t));
                            }
                        }
                        messenger.WriteTaskingMessage();
                    }
                    catch (ObjectDisposedException)
                    {
                        ConnectAttemptCount++;
                        messenger.QueueTaskingMessage(new GruntTaskingMessageResponse(GruntTaskingStatus.Completed, "").ToJson());
                        messenger.WriteTaskingMessage();
                    }
                    catch (Exception e)
                    {
                        ConnectAttemptCount++;
                        Console.Error.WriteLine("Loop Exception: " + e.GetType().ToString() + " " + e.Message + Environment.NewLine + e.StackTrace);
                    }
                    if (ConnectAttemptCount >= ConnectAttempts) { return; }
                    if (KillDate.CompareTo(DateTime.Now) < 0) { return; }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Outer Exception: " + e.Message + Environment.NewLine + e.StackTrace);
            }
        }

19 Source : JValue.cs
with MIT License
from CragonGame

private static int Compare(JTokenType valueType, object objA, object objB)
    {
      if (objA == null && objB == null)
        return 0;
      if (objA != null && objB == null)
        return 1;
      if (objA == null && objB != null)
        return -1;

      switch (valueType)
      {
        case JTokenType.Integer:
          if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
            return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
          else if (objA is float || objB is float || objA is double || objB is double)
            return CompareFloat(objA, objB);
          else
            return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture));
        case JTokenType.Float:
          return CompareFloat(objA, objB);
        case JTokenType.Comment:
        case JTokenType.String:
        case JTokenType.Raw:
          string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture);
          string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture);

          return s1.CompareTo(s2);
        case JTokenType.Boolean:
          bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture);
          bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture);

          return b1.CompareTo(b2);
        case JTokenType.Date:
          if (objA is DateTime)
          {
            DateTime date1 = Convert.ToDateTime(objA, CultureInfo.InvariantCulture);
            DateTime date2 = Convert.ToDateTime(objB, CultureInfo.InvariantCulture);

            return date1.CompareTo(date2);
          }
          else
          {
            if (!(objB is DateTimeOffset))
              throw new ArgumentException("Object must be of type DateTimeOffset.");

            DateTimeOffset date1 = (DateTimeOffset) objA;
            DateTimeOffset date2 = (DateTimeOffset) objB;

            return date1.CompareTo(date2);
          }
        case JTokenType.Bytes:
          if (!(objB is byte[]))
            throw new ArgumentException("Object must be of type byte[].");

          byte[] bytes1 = objA as byte[];
          byte[] bytes2 = objB as byte[];
          if (bytes1 == null)
            return -1;
          if (bytes2 == null)
            return 1;

          return MiscellaneousUtils.ByteArrayCompare(bytes1, bytes2);
        case JTokenType.Guid:
          if (!(objB is Guid))
            throw new ArgumentException("Object must be of type Guid.");

          Guid guid1 = (Guid) objA;
          Guid guid2 = (Guid) objB;

          return guid1.CompareTo(guid2);
        case JTokenType.Uri:
          if (!(objB is Uri))
            throw new ArgumentException("Object must be of type Uri.");

          Uri uri1 = (Uri)objA;
          Uri uri2 = (Uri)objB;

          return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString());
        case JTokenType.TimeSpan:
          if (!(objB is TimeSpan))
            throw new ArgumentException("Object must be of type TimeSpan.");

          TimeSpan ts1 = (TimeSpan)objA;
          TimeSpan ts2 = (TimeSpan)objB;

          return ts1.CompareTo(ts2);
        default:
          throw MiscellaneousUtils.CreateArgumentOutOfRangeException("valueType", valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
      }
    }

19 Source : BsonValue.cs
with Apache License 2.0
from cs-util-com

public virtual int CompareTo(BsonValue other, Collation collation)
        {
            // first, test if types are different
            if (this.Type != other.Type)
            {
                // if both values are number, convert them to Decimal (128 bits) to compare
                // it's the slowest way, but more secure
                if (this.IsNumber && other.IsNumber)
                {
                    return Convert.ToDecimal(this.RawValue).CompareTo(Convert.ToDecimal(other.RawValue));
                }
                // if not, order by sort type order
                else
                {
                    return this.Type.CompareTo(other.Type);
                }
            }

            // for both values with same data type just compare
            switch (this.Type)
            {
                case BsonType.Null:
                case BsonType.MinValue:
                case BsonType.MaxValue:
                    return 0;

                case BsonType.Int32: return this.AsInt32.CompareTo(other.AsInt32);
                case BsonType.Int64: return this.AsInt64.CompareTo(other.AsInt64);
                case BsonType.Double: return this.AsDouble.CompareTo(other.AsDouble);
                case BsonType.Decimal: return this.AsDecimal.CompareTo(other.AsDecimal);

                case BsonType.String: return collation.Compare(this.replacedtring, other.replacedtring);

                case BsonType.Doreplacedent: return this.AsDoreplacedent.CompareTo(other);
                case BsonType.Array: return this.AsArray.CompareTo(other);

                case BsonType.Binary: return this.AsBinary.BinaryCompareTo(other.AsBinary);
                case BsonType.ObjectId: return this.AsObjectId.CompareTo(other.AsObjectId);
                case BsonType.Guid: return this.AsGuid.CompareTo(other.AsGuid);

                case BsonType.Boolean: return this.AsBoolean.CompareTo(other.AsBoolean);
                case BsonType.DateTime:
                    var d0 = this.AsDateTime;
                    var d1 = other.AsDateTime;
                    if (d0.Kind != DateTimeKind.Utc) d0 = d0.ToUniversalTime();
                    if (d1.Kind != DateTimeKind.Utc) d1 = d1.ToUniversalTime();
                    return d0.CompareTo(d1);

                default: throw new NotImplementedException();
            }
        }

19 Source : DetailsListSample.cs
with MIT License
from curiosity-ai

public int CompareTo(DetailsListSampleFileItem other, string columnSortingKey)
        {
            if (other == null)
            {
                throw new ArgumentException(nameof(other));
            }

            if (columnSortingKey.Equals(nameof(FileIcon)))
            {
                return FileIcon.CompareTo(other.FileIcon);
            }

            if (columnSortingKey.Equals(nameof(FileName)))
            {
                return string.Compare(FileName, other.FileName, StringComparison.Ordinal);
            }

            if (columnSortingKey.Equals(nameof(DateModified)))
            {
                return DateModified.CompareTo(other.DateModified);
            }

            if (columnSortingKey.Equals(nameof(ModifiedBy)))
            {
                return string.Compare(FileName, other.FileName, StringComparison.Ordinal);
            }

            if (columnSortingKey.Equals(nameof(FileSize)))
            {
                return FileSize.CompareTo(other.FileSize);
            }

            throw new InvalidOperationException($"Can not match {columnSortingKey} to current list item");
        }

19 Source : TaskScheduler.cs
with GNU General Public License v3.0
from CypherCore

public int CompareTo(Task other)
        {
            return _end.CompareTo(other._end);
        }

19 Source : BsonValue.cs
with GNU General Public License v3.0
from Cytoid

public virtual int CompareTo(BsonValue other, Collation collation)
        {
            // first, test if types are different
            if (this.Type != other.Type)
            {
                // if both values are number, convert them to Decimal (128 bits) to compare
                // it's the slowest way, but more secure
                if (this.IsNumber && other.IsNumber)
                {
                    return Convert.ToDecimal(this.RawValue).CompareTo(Convert.ToDecimal(other.RawValue));
                }
                // if not, order by sort type order
                else
                {
                    var result = this.Type.CompareTo(other.Type);
                    return result < 0 ? -1 : result > 0 ? +1 : 0;
                }
            }

            // for both values with same data type just compare
            switch (this.Type)
            {
                case BsonType.Null:
                case BsonType.MinValue:
                case BsonType.MaxValue:
                    return 0;

                case BsonType.Int32: return this.AsInt32.CompareTo(other.AsInt32);
                case BsonType.Int64: return this.AsInt64.CompareTo(other.AsInt64);
                case BsonType.Double: return this.AsDouble.CompareTo(other.AsDouble);
                case BsonType.Decimal: return this.AsDecimal.CompareTo(other.AsDecimal);

                case BsonType.String: return collation.Compare(this.replacedtring, other.replacedtring);

                case BsonType.Doreplacedent: return this.AsDoreplacedent.CompareTo(other);
                case BsonType.Array: return this.AsArray.CompareTo(other);

                case BsonType.Binary: return this.AsBinary.BinaryCompareTo(other.AsBinary);
                case BsonType.ObjectId: return this.AsObjectId.CompareTo(other.AsObjectId);
                case BsonType.Guid: return this.AsGuid.CompareTo(other.AsGuid);

                case BsonType.Boolean: return this.AsBoolean.CompareTo(other.AsBoolean);
                case BsonType.DateTime:
                    var d0 = this.AsDateTime;
                    var d1 = other.AsDateTime;
                    if (d0.Kind != DateTimeKind.Utc) d0 = d0.ToUniversalTime();
                    if (d1.Kind != DateTimeKind.Utc) d1 = d1.ToUniversalTime();
                    return d0.CompareTo(d1);

                default: throw new NotImplementedException();
            }
        }

19 Source : Pair.cs
with GNU Lesser General Public License v3.0
from czsgeo

public int CompareTo(TimedValue<TVal> other)
        {
            return Time.CompareTo(other.Time);
        }

19 Source : Time.cs
with GNU Lesser General Public License v3.0
from czsgeo

public int CompareTo(Time other)
        {
            int val = this.DateTime.CompareTo(other.DateTime);
            if(val == 0)
            {
                return FractionOfMilliSecond.CompareTo(other.FractionOfMilliSecond);
            }
            return val;
        }

19 Source : time_t.cs
with MIT License
from dahall

public int CompareTo(DateTime other) => Value.CompareTo(other);

19 Source : DATE.cs
with MIT License
from dahall

public int CompareTo(DATE other) => Value.CompareTo(other.Value);

19 Source : CacheItem.cs
with GNU Affero General Public License v3.0
from Daniele122898

public bool IsValid()
        {
            if (this.ValidUntil.HasValue && this.ValidUntil.Value.CompareTo(DateTime.UtcNow) <= 0)
            {
                return false;
            }

            return true;
        }

19 Source : Rfc3281CertPathUtilities.cs
with MIT License
from dcomms

private static void CheckCrl(
			DistributionPoint			dp,
			IX509AttributeCertificate	attrCert,
			PkixParameters				paramsPKIX,
			DateTime					validDate,
			X509Certificate				issuerCert,
			CertStatus					certStatus,
			ReasonsMask					reasonMask,
			IList						certPathCerts)
		{
			/*
			* 4.3.6 No Revocation Available
			* 
			* The noRevAvail extension, defined in [X.509-2000], allows an AC
			* issuer to indicate that no revocation information will be made
			* available for this AC.
			*/
			if (attrCert.GetExtensionValue(X509Extensions.NoRevAvail) != null)
			{
				return;
			}

			DateTime currentDate = DateTime.UtcNow;
			if (validDate.CompareTo(currentDate) > 0)
			{
				throw new Exception("Validation time is in future.");
			}

			// (a)
			/*
			* We always get timely valid CRLs, so there is no step (a) (1).
			* "locally cached" CRLs are replacedumed to be in getStore(), additional
			* CRLs must be enabled in the ExtendedPkixParameters and are in
			* getAdditionalStore()
			*/
			ISet crls = PkixCertPathValidatorUtilities.GetCompleteCrls(dp, attrCert,
				currentDate, paramsPKIX);
			bool validCrlFound = false;
			Exception lastException = null;

			IEnumerator crl_iter = crls.GetEnumerator();

			while (crl_iter.MoveNext()
				&& certStatus.Status == CertStatus.Unrevoked
				&& !reasonMask.IsAllReasons)
			{
				try
				{
					X509Crl crl = (X509Crl) crl_iter.Current;

					// (d)
					ReasonsMask interimReasonsMask = Rfc3280CertPathUtilities.ProcessCrlD(crl, dp);

					// (e)
					/*
					* The reasons mask is updated at the end, so only valid CRLs
					* can update it. If this CRL does not contain new reasons it
					* must be ignored.
					*/
					if (!interimReasonsMask.HasNewReasons(reasonMask))
					{
						continue;
					}

					// (f)
					ISet keys = Rfc3280CertPathUtilities.ProcessCrlF(crl, attrCert,
						null, null, paramsPKIX, certPathCerts);
					// (g)
					AsymmetricKeyParameter pubKey = Rfc3280CertPathUtilities.ProcessCrlG(crl, keys);

					X509Crl deltaCRL = null;

					if (paramsPKIX.IsUseDeltasEnabled)
					{
						// get delta CRLs
						ISet deltaCRLs = PkixCertPathValidatorUtilities.GetDeltaCrls(
							currentDate, paramsPKIX, crl);
						// we only want one valid delta CRL
						// (h)
						deltaCRL = Rfc3280CertPathUtilities.ProcessCrlH(deltaCRLs, pubKey);
					}

					/*
					* CRL must be be valid at the current time, not the validation
					* time. If a certificate is revoked with reason keyCompromise,
					* cACompromise, it can be used for forgery, also for the past.
					* This reason may not be contained in older CRLs.
					*/

					/*
					* in the chain model signatures stay valid also after the
					* certificate has been expired, so they do not have to be in
					* the CRL vality time
					*/
					if (paramsPKIX.ValidityModel != PkixParameters.ChainValidityModel)
					{
						/*
						* if a certificate has expired, but was revoked, it is not
						* more in the CRL, so it would be regarded as valid if the
						* first check is not done
						*/
						if (attrCert.NotAfter.CompareTo(crl.ThisUpdate) < 0)
						{
							throw new Exception(
								"No valid CRL for current time found.");
						}
					}

					Rfc3280CertPathUtilities.ProcessCrlB1(dp, attrCert, crl);

					// (b) (2)
					Rfc3280CertPathUtilities.ProcessCrlB2(dp, attrCert, crl);

					// (c)
					Rfc3280CertPathUtilities.ProcessCrlC(deltaCRL, crl, paramsPKIX);

					// (i)
					Rfc3280CertPathUtilities.ProcessCrlI(validDate, deltaCRL,
						attrCert, certStatus, paramsPKIX);

					// (j)
					Rfc3280CertPathUtilities.ProcessCrlJ(validDate, crl, attrCert,
						certStatus);

					// (k)
					if (certStatus.Status == CrlReason.RemoveFromCrl)
					{
						certStatus.Status = CertStatus.Unrevoked;
					}

					// update reasons mask
					reasonMask.AddReasons(interimReasonsMask);
					validCrlFound = true;
				}
				catch (Exception e)
				{
					lastException = e;
				}
			}
			if (!validCrlFound)
			{
				throw lastException;
			}
		}

19 Source : X509CertStoreSelector.cs
with MIT License
from dcomms

public virtual bool Match(
			object obj)
		{
			X509Certificate c = obj as X509Certificate;

			if (c == null)
				return false;

			if (!MatchExtension(authorityKeyIdentifier, c, X509Extensions.AuthorityKeyIdentifier))
				return false;

			if (basicConstraints != -1)
			{
				int bc = c.GetBasicConstraints();

				if (basicConstraints == -2)
				{
					if (bc != -1)
						return false;
				}
				else
				{
					if (bc < basicConstraints)
						return false;
				}
			}

			if (certificate != null && !certificate.Equals(c))
				return false;

			if (certificateValid != null && !c.IsValid(certificateValid.Value))
				return false;

			if (extendedKeyUsage != null)
			{
				IList eku = c.GetExtendedKeyUsage();

				// Note: if no extended key usage set, all key purposes are implicitly allowed

				if (eku != null)
				{
					foreach (DerObjectIdentifier oid in extendedKeyUsage)
					{
						if (!eku.Contains(oid.Id))
							return false;
					}
				}
			}

			if (issuer != null && !issuer.Equivalent(c.IssuerDN, !ignoreX509NameOrdering))
				return false;

			if (keyUsage != null)
			{
				bool[] ku = c.GetKeyUsage();

				// Note: if no key usage set, all key purposes are implicitly allowed

				if (ku != null)
				{
					for (int i = 0; i < 9; ++i)
					{
						if (keyUsage[i] && !ku[i])
							return false;
					}
				}
			}

			if (policy != null)
			{
				Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.CertificatePolicies);
				if (extVal == null)
					return false;

				Asn1Sequence certPolicies = Asn1Sequence.GetInstance(
					X509ExtensionUtilities.FromExtensionValue(extVal));

				if (policy.Count < 1 && certPolicies.Count < 1)
					return false;

				bool found = false;
				foreach (PolicyInformation pi in certPolicies)
				{
					if (policy.Contains(pi.PolicyIdentifier))
					{
						found = true;
						break;
					}
				}

				if (!found)
					return false;
			}

			if (privateKeyValid != null)
			{
				Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.PrivateKeyUsagePeriod);
				if (extVal == null)
					return false;

				PrivateKeyUsagePeriod pkup = PrivateKeyUsagePeriod.GetInstance(
					X509ExtensionUtilities.FromExtensionValue(extVal));

				DateTime dt = privateKeyValid.Value;
				DateTime notAfter = pkup.NotAfter.ToDateTime();
				DateTime notBefore = pkup.NotBefore.ToDateTime();

				if (dt.CompareTo(notAfter) > 0 || dt.CompareTo(notBefore) < 0)
					return false;
			}

			if (serialNumber != null && !serialNumber.Equals(c.SerialNumber))
				return false;

            if (subject != null && !subject.Equivalent(c.SubjectDN, !ignoreX509NameOrdering))
				return false;

			if (!MatchExtension(subjectKeyIdentifier, c, X509Extensions.SubjectKeyIdentifier))
				return false;

			if (subjectPublicKey != null && !subjectPublicKey.Equals(GetSubjectPublicKey(c)))
				return false;

			if (subjectPublicKeyAlgID != null
				&& !subjectPublicKeyAlgID.Equals(GetSubjectPublicKey(c).AlgorithmID))
				return false;

			return true;
		}

19 Source : X509CrlStoreSelector.cs
with MIT License
from dcomms

public virtual bool Match(
			object obj)
		{
			X509Crl c = obj as X509Crl;

			if (c == null)
				return false;

			if (dateAndTime != null)
			{
				DateTime dt = dateAndTime.Value;
				DateTime tu = c.ThisUpdate;
				DateTimeObject nu = c.NextUpdate;

				if (dt.CompareTo(tu) < 0 || nu == null || dt.CompareTo(nu.Value) >= 0)
					return false;
			}

			if (issuers != null)
			{
				X509Name i = c.IssuerDN;

				bool found = false;

				foreach (X509Name issuer in issuers)
				{
					if (issuer.Equivalent(i, true))
					{
						found = true;
						break;
					}
				}

				if (!found)
					return false;
			}

			if (maxCrlNumber != null || minCrlNumber != null)
			{
				Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.CrlNumber);
				if (extVal == null)
					return false;

				BigInteger cn = CrlNumber.GetInstance(
					X509ExtensionUtilities.FromExtensionValue(extVal)).PositiveValue;

				if (maxCrlNumber != null && cn.CompareTo(maxCrlNumber) > 0)
					return false;

				if (minCrlNumber != null && cn.CompareTo(minCrlNumber) < 0)
					return false;
			}

			DerInteger dci = null;
			try
			{
				Asn1OctetString bytes = c.GetExtensionValue(X509Extensions.DeltaCrlIndicator);
				if (bytes != null)
				{
					dci = DerInteger.GetInstance(X509ExtensionUtilities.FromExtensionValue(bytes));
				}
			}
			catch (Exception)
			{
				return false;
			}

			if (dci == null)
			{
				if (DeltaCrlIndicatorEnabled)
					return false;
			}
			else
			{
				if (CompleteCrlEnabled)
					return false;

				if (maxBaseCrlNumber != null && dci.PositiveValue.CompareTo(maxBaseCrlNumber) > 0)
					return false;
			}

			if (issuingDistributionPointEnabled)
			{
				Asn1OctetString idp = c.GetExtensionValue(X509Extensions.IssuingDistributionPoint);
				if (issuingDistributionPoint == null)
				{
					if (idp != null)
						return false;
				}
				else
				{
					if (!Arrays.AreEqual(idp.GetOctets(), issuingDistributionPoint))
						return false;
				}
			}

			return true;
		}

19 Source : X509CrlStoreSelector.cs
with MIT License
from dcomms

public virtual bool Match(
			object obj)
		{
			X509Crl c = obj as X509Crl;

			if (c == null)
				return false;

			if (dateAndTime != null)
			{
				DateTime dt = dateAndTime.Value;
				DateTime tu = c.ThisUpdate;
				DateTimeObject nu = c.NextUpdate;

				if (dt.CompareTo(tu) < 0 || nu == null || dt.CompareTo(nu.Value) >= 0)
					return false;
			}

			if (issuers != null)
			{
				X509Name i = c.IssuerDN;

				bool found = false;

				foreach (X509Name issuer in issuers)
				{
					if (issuer.Equivalent(i, true))
					{
						found = true;
						break;
					}
				}

				if (!found)
					return false;
			}

			if (maxCrlNumber != null || minCrlNumber != null)
			{
				Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.CrlNumber);
				if (extVal == null)
					return false;

				BigInteger cn = CrlNumber.GetInstance(
					X509ExtensionUtilities.FromExtensionValue(extVal)).PositiveValue;

				if (maxCrlNumber != null && cn.CompareTo(maxCrlNumber) > 0)
					return false;

				if (minCrlNumber != null && cn.CompareTo(minCrlNumber) < 0)
					return false;
			}

			DerInteger dci = null;
			try
			{
				Asn1OctetString bytes = c.GetExtensionValue(X509Extensions.DeltaCrlIndicator);
				if (bytes != null)
				{
					dci = DerInteger.GetInstance(X509ExtensionUtilities.FromExtensionValue(bytes));
				}
			}
			catch (Exception)
			{
				return false;
			}

			if (dci == null)
			{
				if (DeltaCrlIndicatorEnabled)
					return false;
			}
			else
			{
				if (CompleteCrlEnabled)
					return false;

				if (maxBaseCrlNumber != null && dci.PositiveValue.CompareTo(maxBaseCrlNumber) > 0)
					return false;
			}

			if (issuingDistributionPointEnabled)
			{
				Asn1OctetString idp = c.GetExtensionValue(X509Extensions.IssuingDistributionPoint);
				if (issuingDistributionPoint == null)
				{
					if (idp != null)
						return false;
				}
				else
				{
					if (!Arrays.AreEqual(idp.GetOctets(), issuingDistributionPoint))
						return false;
				}
			}

			return true;
		}

19 Source : X509Certificate.cs
with MIT License
from dcomms

public virtual bool IsValid(
			DateTime time)
        {
            return time.CompareTo(NotBefore) >= 0 && time.CompareTo(NotAfter) <= 0;
        }

19 Source : X509Certificate.cs
with MIT License
from dcomms

public virtual void CheckValidity(
			DateTime time)
		{
			if (time.CompareTo(NotAfter) > 0)
				throw new CertificateExpiredException("certificate expired on " + c.EndDate.GetTime());
			if (time.CompareTo(NotBefore) < 0)
				throw new CertificateNotYetValidException("certificate not valid until " + c.StartDate.GetTime());
		}

See More Examples