示例#1
0
        private void cmdChangePassword_Inquire(object sender, FndCommandInquireEventArgs e)
        {
            #region Local Variables
            SalNumber nRow = 0;
            #endregion

            #region Actions
            if (!(Ifs.Fnd.ApplicationForms.Var.Security.IsDataSourceAvailable(Pal.GetActiveInstanceName("dlgLchChangePassword"))))
            {
                ((FndCommand)sender).Enabled = false;
                return;
            }
            if (!(Sal.TblAnyRows(this, Sys.ROW_Selected, 0)))
            {
                ((FndCommand)sender).Enabled = false;
                return;
            }

            nRow = Sys.TBL_MinRow;
            if (Sal.TblFindNextRow(this, ref nRow, Sys.ROW_Selected, 0))
            {
                if (Sal.TblFindNextRow(this, ref nRow, Sys.ROW_Selected, 0))
                {
                    ((FndCommand)sender).Enabled = false;
                    return;
                }
            }
            ((FndCommand)sender).Enabled = true;

            #endregion
        }
        public void TruncateJournal_WhenCalled_ShouldTruncate()
        {
            var file = Path.Combine(NewDataPath(forceCreateDir: true), $"test_journal.{Guid.NewGuid()}");

            PalFlags.FailCodes ret;

            const long initSize = 2 * 4096L;

            ret = Pal.rvn_open_journal_for_writes(file, PalFlags.JournalMode.Safe, initSize, PalFlags.DurabilityMode.DurabililtySupported, out var handle, out var actualSize, out var errno);
            if (ret != PalFlags.FailCodes.Success)
            {
                PalHelper.ThrowLastError(ret, errno, "");
            }

            const long truncateSize = 4096L;

            ret = Pal.rvn_truncate_journal(handle, truncateSize, out errno);
            if (ret != PalFlags.FailCodes.Success)
            {
                PalHelper.ThrowLastError(ret, errno, "");
            }

            var actual = new FileInfo(file).Length;

            Assert.Equal(truncateSize, actual);

            handle.Dispose();
        }
        public void OpenJournal_WhenCalled_ShouldCreateFile()
        {
            var file     = Path.Combine(NewDataPath(forceCreateDir: true), $"test_journal.{Guid.NewGuid()}");
            var fileSize = 4096L;

            PalFlags.FailCodes ret;

            ret = Pal.rvn_open_journal_for_writes(file, PalFlags.JournalMode.Safe, fileSize, PalFlags.DurabilityMode.DurabililtySupported, out var handle, out var actualSize, out var errno);
            if (ret != PalFlags.FailCodes.Success)
            {
                PalHelper.ThrowLastError(ret, errno, "");
            }

            Assert.Equal(PalFlags.FailCodes.Success, ret);

            Assert.True(File.Exists(file));
            Assert.False(handle.IsInvalid);

            handle.Dispose();

            var length = new FileInfo(file).Length;

            Assert.True(length >= 4096L);
            Assert.Equal(length, actualSize);
        }
示例#4
0
        public unsafe void MMap_WhenLinkBroken_ShouldFailWithInfoError()
        {
            var basicPath = NewDataPath(forceCreateDir: true);

            var linkTarget = Path.Combine(basicPath, "brokentarget");

            var link = Path.Combine(basicPath, "brokenlink");

            symlink(linkTarget, link);

            var filePath     = Path.Combine(link, $"test_journal.{Guid.NewGuid()}");
            var initFileSize = 4096L;
            var mmapOptions  = PalFlags.MmapOptions.CopyOnWrite;

            var       ret = PalFlags.FailCodes.None;
            Exception ex  = Assert.Throws <InvalidOperationException>(() =>
            {
                ret = Pal.rvn_create_and_mmap64_file(filePath, initFileSize, mmapOptions, out var handle, out var baseAddress, out var actualFileSize, out var errorCode);
                using (handle)
                {
                    if (ret != PalFlags.FailCodes.Success)
                    {
                        PalHelper.ThrowLastError(ret, errorCode, "");
                    }

                    ret = Pal.rvn_unmap(mmapOptions, baseAddress, actualFileSize, out errorCode);
                    if (ret != PalFlags.FailCodes.Success)
                    {
                        PalHelper.ThrowLastError(ret, errorCode, "");
                    }
                }
            });

            Assert.Equal(PalFlags.FailCodes.FailBrokenLink, ret);
        }
        public unsafe void ReadJournal_WhenDo_ShouldRead()
        {
            var       file     = Path.Combine(NewDataPath(forceCreateDir: true), $"test_journal.{Guid.NewGuid()}");
            const int fileSize = 3 * 4096;
            const int offset   = 4096;
            const int length   = 4096;

            PalFlags.FailCodes ret;

            ret = Pal.rvn_open_journal_for_writes(file, PalFlags.JournalMode.Safe, fileSize, PalFlags.DurabilityMode.DurabililtySupported, out var handle, out var actualSize, out var errno);
            if (ret != PalFlags.FailCodes.Success)
            {
                PalHelper.ThrowLastError(ret, errno, "");
            }

            var buffer = PlatformSpecific.NativeMemory.Allocate4KbAlignedMemory(4096, out var stats);

            for (var i = 0; i < 4096 / sizeof(int); i++)
            {
                *((int *)buffer + i) = i;
            }
            var expected = new byte[fileSize];

            Marshal.Copy((IntPtr)buffer, expected, offset, length);
            try
            {
                ret = Pal.rvn_write_journal(handle, buffer, length, offset, out errno);
                if (ret != PalFlags.FailCodes.Success)
                {
                    PalHelper.ThrowLastError(ret, errno, "");
                }
            }
            finally
            {
                PlatformSpecific.NativeMemory.Free4KbAlignedMemory(buffer, 4096, stats);
            }

            handle.Dispose();

            var actual = new byte[length];

            fixed(byte *pActual = actual)
            {
                ret = Pal.rvn_open_journal_for_reads(file, out var rHandle, out errno);
                if (ret != PalFlags.FailCodes.Success)
                {
                    PalHelper.ThrowLastError(ret, errno, "");
                }

                ret = Pal.rvn_read_journal(rHandle, pActual, length, offset, out var readActualSize, out errno);
                if (ret != PalFlags.FailCodes.Success)
                {
                    PalHelper.ThrowLastError(ret, errno, "");
                }

                Assert.Equal(length, readActualSize);
            }

            Assert.Equal(expected, expected);
        }
示例#6
0
        public unsafe void MMap_WhenLinkEndOfPath_ShouldSucceed()
        {
            var basicPath = NewDataPath(forceCreateDir: true);

            var linkTarget = Path.Combine(basicPath, "linkTarget");

            Directory.CreateDirectory(linkTarget);

            var link = Path.Combine(basicPath, "l");

            symlink(linkTarget, link);

            var filePath     = Path.Combine(link, $"test_journal.{Guid.NewGuid()}");
            var initFileSize = 4096L;
            var mmapOptions  = PalFlags.MmapOptions.CopyOnWrite;

            var ret = Pal.rvn_create_and_mmap64_file(filePath, initFileSize, mmapOptions, out var handle, out var baseAddress, out var actualFileSize, out var errorCode);

            if (ret != PalFlags.FailCodes.Success)
            {
                PalHelper.ThrowLastError(ret, errorCode, "");
            }

            ret = Pal.rvn_unmap(mmapOptions, baseAddress, actualFileSize, out errorCode);
            if (ret != PalFlags.FailCodes.Success)
            {
                PalHelper.ThrowLastError(ret, errorCode, "");
            }

            handle.Dispose();
        }
示例#7
0
 public string LoadPal()
 {
     try {
         List <Pal> xx = new List <Pal>();
         using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + Server.MapPath("~/App_Data/" + dataBase))) {
             connection.Open();
             string sql = @"SELECT code, title, palDescription, palMin, palMax FROM pal";
             using (SQLiteCommand command = new SQLiteCommand(sql, connection)) {
                 using (SQLiteDataReader reader = command.ExecuteReader()) {
                     while (reader.Read())
                     {
                         Pal x = new Pal();
                         x.code        = reader.GetValue(0) == DBNull.Value ? "" : reader.GetString(0);
                         x.title       = reader.GetValue(1) == DBNull.Value ? "" : reader.GetString(1);
                         x.description = reader.GetValue(2) == DBNull.Value ? "" : reader.GetString(2);
                         x.min         = reader.GetValue(3) == DBNull.Value ? 0 : Convert.ToDouble(reader.GetString(3));
                         x.max         = reader.GetValue(4) == DBNull.Value ? 0 : Convert.ToDouble(reader.GetString(4));
                         x.value       = Math.Round((x.min + x.max) / 2, 2);
                         xx.Add(x);
                     }
                 }
             }
             connection.Close();
         }
         return(JsonConvert.SerializeObject(xx, Formatting.None));
     } catch (Exception e) { return(JsonConvert.SerializeObject(e.Message, Formatting.None)); }
 }
示例#8
0
        public unsafe void MapFile_WhenCalled_ShouldSuccess()
        {
            //TODO To remove when mmap functions are implemented in windows
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) == false)
            {
                return;
            }

            var path         = Path.Combine(NewDataPath(forceCreateDir: true), $"test_journal.{Guid.NewGuid()}");
            var initFileSize = 4096L;
            var mmapOptions  = PalFlags.MmapOptions.CopyOnWrite;

            var ret = Pal.rvn_create_and_mmap64_file(path, initFileSize, mmapOptions, out var handle, out var baseAddress, out var actualFileSize, out var errorCode);

            if (ret != PalFlags.FailCodes.Success)
            {
                PalHelper.ThrowLastError(ret, errorCode, "");
            }

            ret = Pal.rvn_unmap(mmapOptions, baseAddress, actualFileSize, out errorCode);
            if (ret != PalFlags.FailCodes.Success)
            {
                PalHelper.ThrowLastError(ret, errorCode, "");
            }

            handle.Dispose();
        }
示例#9
0
        /// <summary>
        /// Combines a private key with the public key of an <see cref="ECDiffieHellman" />
        /// certificate to generate a new ECDiffieHellman certificate.
        /// </summary>
        /// <param name="privateKey">The private ECDiffieHellman key.</param>
        /// <returns>
        /// A new ECDiffieHellman certificate with the <see cref="HasPrivateKey" /> property set to <see langword="true"/>.
        /// The current certificate isn't modified.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="privateKey" /> is <see langword="null"/>.</exception>
        /// <exception cref="InvalidOperationException">
        /// The certificate already has an associated private key.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// <para>
        ///   The certificate doesn't have a public key.
        /// </para>
        /// <para> -or- </para>
        /// <para>
        ///   The specified private key doesn't match the public key for this certificate.
        /// </para>
        /// </exception>
        public X509Certificate2 CopyWithPrivateKey(ECDiffieHellman privateKey)
        {
            if (privateKey is null)
            {
                throw new ArgumentNullException(nameof(privateKey));
            }

            if (HasPrivateKey)
            {
                throw new InvalidOperationException(SR.Cryptography_Cert_AlreadyHasPrivateKey);
            }

            using (ECDiffieHellman? publicKey = GetECDiffieHellmanPublicKey())
            {
                if (publicKey is null)
                {
                    throw new ArgumentException(SR.Cryptography_PrivateKey_WrongAlgorithm);
                }

                if (!Helpers.AreSamePublicECParameters(publicKey.ExportParameters(false), privateKey.ExportParameters(false)))
                {
                    throw new ArgumentException(SR.Cryptography_PrivateKey_DoesNotMatch, nameof(privateKey));
                }
            }

            ICertificatePal pal = Pal.CopyWithPrivateKey(privateKey);

            return(new X509Certificate2(pal));
        }
示例#10
0
        public static DiskSpaceResult GetDiskSpaceInfo(string pathToCheck, DriveInfoBase driveInfoBase = null)
        {
            if (string.IsNullOrEmpty(pathToCheck))
            {
                return(null);
            }

            var result = Pal.rvn_get_path_disk_space(pathToCheck, out var totalFreeBytes, out var totalDiskBytes, out int error);

            if (result != PalFlags.FailCodes.Success)
            {
                if (Logger.IsInfoEnabled)
                {
                    Logger.Info($"Failed to get file system statistics for path: {pathToCheck}, error: {error}");
                }

                return(null);
            }

            return(new DiskSpaceResult
            {
                DriveName = driveInfoBase?.DriveName,
                VolumeLabel = GetVolumeLabel(driveInfoBase?.DriveName),
                TotalFreeSpace = new Size((long)totalFreeBytes, SizeUnit.Bytes),
                TotalSize = new Size((long)totalDiskBytes, SizeUnit.Bytes)
            });
        }
示例#11
0
 public void DiscardDataOnDisk()
 {
     if (AllocationInfos != null)
     {
         Pal.rvn_discard_virtual_memory(AllocationInfos[0].BaseAddress, AllocationInfos[0].Size, out _);
     }
 }
示例#12
0
        public unsafe void rvn_get_error_string_WhenCalled_ShouldCreateFile()
        {
            var errBuffer = new byte[256];

            fixed(byte *p = errBuffer)
            {
                var size = Pal.rvn_get_error_string(
                    0,
                    p,
                    256,
                    out var errno
                    );

                var errorString = Encoding.UTF8.GetString(p, size);

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    Assert.StartsWith("The operation completed successfully.", errorString);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    Assert.StartsWith("Success", errorString);
                }
            }
        }
示例#13
0
        static TestBase()
        {
            LicenseManager.IgnoreProcessorAffinityChanges = true;
            NativeMemory.GetCurrentUnmanagedThreadId      = () => (ulong)Pal.rvn_get_current_thread_id();
#if DEBUG2
            TaskScheduler.UnobservedTaskException += (sender, args) =>
            {
                if (args.Observed)
                {
                    return;
                }

                var e = args.Exception.ExtractSingleInnerException();

                var sb = new StringBuilder();
                sb.AppendLine("===== UNOBSERVED TASK EXCEPTION =====");
                sb.AppendLine(e.ExceptionToString(null));
                sb.AppendLine("=====================================");

                Console.WriteLine(sb.ToString());
            };
#endif
            if (PlatformDetails.RunningOnPosix == false &&
                PlatformDetails.Is32Bits) // RavenDB-13655
            {
                ThreadPool.SetMinThreads(25, 25);
                ThreadPool.SetMaxThreads(125, 125);
            }
            else
            {
                ThreadPool.SetMinThreads(250, 250);
            }

            var maxNumberOfConcurrentTests = Math.Max(ProcessorInfo.ProcessorCount / 2, 2);

            RequestExecutor.RemoteCertificateValidationCallback += (sender, cert, chain, errors) => true;

            var fileInfo = new FileInfo(XunitConfigurationFile);
            if (fileInfo.Exists)
            {
                using (var file = File.OpenRead(XunitConfigurationFile))
                    using (var sr = new StreamReader(file))
                    {
                        var json = JObject.Parse(sr.ReadToEnd());

                        if (json.TryGetValue("maxRunningTests", out var testsToken))
                        {
                            maxNumberOfConcurrentTests = testsToken.Value <int>();
                        }
                        else if (json.TryGetValue("maxParallelThreads", out var threadsToken))
                        {
                            maxNumberOfConcurrentTests = threadsToken.Value <int>();
                        }
                    }
            }

            Console.WriteLine("Max number of concurrent tests is: " + maxNumberOfConcurrentTests);
            ConcurrentTestsSemaphore = new SemaphoreSlim(maxNumberOfConcurrentTests, maxNumberOfConcurrentTests);
        }
示例#14
0
        public void Truncate(long size)
        {
            var result = Pal.rvn_truncate_journal(_writeHandle, size, out var error);

            if (result != PalFlags.FailCodes.Success)
            {
                PalHelper.ThrowLastError(result, error, $"Attempted to write to journal file - Path: {FileName.FullPath} Size: {size}");
            }
        }
示例#15
0
        public void PalUnitTes4()
        {
            string TestString = "R,,,     ace,, CAR";
            bool   expected   = true;

            bool actual = Pal.Check(TestString);

            Assert.AreEqual(expected, actual);
        }
示例#16
0
 public string GetPalDetails(double palValue)
 {
     try {
         Pal x = new Pal();
         x = GetPal(palValue);
         string json = JsonConvert.SerializeObject(x, Formatting.None);
         return(json);
     } catch (Exception e) { return("Error: " + e); }
 }
示例#17
0
        public void PalUnitTes1()
        {
            string TestString = "racecar";
            bool   expected   = true;

            bool actual = Pal.Check(TestString);

            Assert.AreEqual(expected, actual);
        }
示例#18
0
        static RachisConsensusTestBase()
        {
            XunitLogging.RedirectStreams = false;
            XunitLogging.Init();
            XunitLogging.EnableExceptionCapture();

            NativeMemory.GetCurrentUnmanagedThreadId = () => (ulong)Pal.rvn_get_current_thread_id();
            JsonDeserializationCluster.Commands.Add(nameof(TestCommand), JsonDeserializationBase.GenerateJsonDeserializationRoutine <TestCommand>());
        }
示例#19
0
        public void PalUnitTest2()
        {
            string TestString = "never odd, or even";
            bool   expected   = true;

            bool actual = Pal.Check(TestString);

            Assert.AreEqual(expected, actual);
        }
        static unsafe RachisConsensusTestBase()
        {
            XunitLogging.RedirectStreams = false;
            XunitLogging.Init();
            XunitLogging.EnableExceptionCapture();

            NativeMemory.GetCurrentUnmanagedThreadId = () => (ulong)Pal.rvn_get_current_thread_id();
            Lucene.Net.Util.UnmanagedStringArray.Segment.AllocateMemory = NativeMemory.AllocateMemory;
            Lucene.Net.Util.UnmanagedStringArray.Segment.FreeMemory     = NativeMemory.Free;
            JsonDeserializationCluster.Commands.Add(nameof(TestCommand), JsonDeserializationBase.GenerateJsonDeserializationRoutine <TestCommand>());
        }
示例#21
0
 public string GetPalDetails(double palValue)
 {
     try {
         Pal x = new Pal();
         x = GetPal(palValue);
         return(JsonConvert.SerializeObject(x, Formatting.None));
     } catch (Exception e) {
         L.SendErrorLog(e, palValue.ToString(), null, "Calculations", "GetPalDetails");
         return(JsonConvert.SerializeObject(e.Message, Formatting.None));
     }
 }
示例#22
0
        public void DiscardDataOnDisk()
        {
            if (_pager.Options.DiscardVirtualMemory == false)
            {
                return;
            }

            if (AllocationInfos != null)
            {
                Pal.rvn_discard_virtual_memory(AllocationInfos[0].BaseAddress, AllocationInfos[0].Size, out _);
            }
        }
示例#23
0
        public static void loadImmediate(ushort nc1, ushort nc2, ushort nc3, ushort nc4)
        {
            Pal p = new Pal();

            p.make();
            //five-bit color
            p.colors[0] = Color.FromArgb(((nc1 & 0x1F) << 3), (((nc1 >> 5) & 0x1F) << 3), (((nc1 >> 10) & 0x1F) << 3));
            p.colors[1] = Color.FromArgb(((nc2 & 0x1F) << 3), (((nc2 >> 5) & 0x1F) << 3), (((nc2 >> 10) & 0x1F) << 3));
            p.colors[2] = Color.FromArgb(((nc3 & 0x1F) << 3), (((nc3 >> 5) & 0x1F) << 3), (((nc3 >> 10) & 0x1F) << 3));
            p.colors[3] = Color.FromArgb(((nc4 & 0x1F) << 3), (((nc4 >> 5) & 0x1F) << 3), (((nc4 >> 10) & 0x1F) << 3));
            pals.Add(p);
        }
示例#24
0
        private void GetCupuNumberSpreadsPal(int count)
        {
            var x = 0L;

            for (int i = 0; i < count; i++)
            {
                x += Pal.GetCurrentCoreId();
                // Pal.FlushCurrentCpuId();
            }

            Assert.IsTrue(x >= 0, "Spreads: " + x);
        }
示例#25
0
        public virtual byte[] Export(X509ContentType contentType, SecureString?password)
        {
            VerifyContentType(contentType);

            if (Pal == null)
            {
                throw new CryptographicException(ErrorCode.E_POINTER);  // Not the greatest error, but needed for backward compat.
            }
            using (var safePasswordHandle = new SafePasswordHandle(password))
            {
                return(Pal.Export(contentType, safePasswordHandle));
            }
        }
示例#26
0
    private Pal GetPalData(SQLiteDataReader reader)
    {
        Pal x = new Pal();

        x.code        = reader.GetValue(0) == DBNull.Value ? "" : reader.GetString(0);
        x.title       = reader.GetValue(1) == DBNull.Value ? "" : reader.GetString(1);
        x.description = reader.GetValue(2) == DBNull.Value ? "" : reader.GetString(2);
        x.min         = reader.GetValue(3) == DBNull.Value ? 0 : Convert.ToDouble(reader.GetString(3));
        x.max         = reader.GetValue(4) == DBNull.Value ? 0 : Convert.ToDouble(reader.GetString(4));
        x.value       = Math.Round((x.min + x.max) / 2, 2);
        x.icon        = GetPalIcon(x.code);
        return(x);
    }
        public void TestMethod1()
        {
            string inputStr = "Race car";
            string answer   = "racecar";

            string notCaseSensitive = inputStr.ToLower();

            Stripper test      = new Stripper();
            String   outputStr = test.StripNonAlphaNumeric(inputStr.Replace(" ", ""));
            Pal      pMoney    = new Pal();

            pMoney.checkPalindrome(outputStr);
            Assert.AreEqual(pMoney.palString, answer);
        }
示例#28
0
        static unsafe RachisConsensusTestBase()
        {
            XunitLogging.RedirectStreams = false;
            XunitLogging.Init();
            XunitLogging.EnableExceptionCapture();

            NativeMemory.GetCurrentUnmanagedThreadId = () => (ulong)Pal.rvn_get_current_thread_id();
            ZstdLib.CreateDictionaryException        = message => new VoronErrorException(message);
            RachisStateMachine.EnableDebugLongCommit = true;

            Lucene.Net.Util.UnmanagedStringArray.Segment.AllocateMemory = NativeMemory.AllocateMemory;
            Lucene.Net.Util.UnmanagedStringArray.Segment.FreeMemory     = NativeMemory.Free;
            JsonDeserializationCluster.Commands.Add(nameof(TestCommand), JsonDeserializationBase.GenerateJsonDeserializationRoutine <TestCommand>());
        }
示例#29
0
        public JournalWriter(StorageEnvironmentOptions options, VoronPathSetting filename, long size, PalFlags.JournalMode mode = PalFlags.JournalMode.Safe)
        {
            _options = options;
            FileName = filename;
            _log     = LoggingSource.Instance.GetLogger <JournalWriter>(options.BasePath.FullPath);

            var result = Pal.rvn_open_journal_for_writes(filename.FullPath, mode, size, options.SupportDurabilityFlags, out _writeHandle, out var actualSize, out var error);

            if (result != PalFlags.FailCodes.Success)
            {
                PalHelper.ThrowLastError(result, error, $"Attempted to open journal file - Path: {filename.FullPath} Size :{size}");
            }

            NumberOfAllocated4Kb = (int)(actualSize / (4 * Constants.Size.Kilobyte));
        }
示例#30
0
 public IActionResult Index()
 {
     if (HttpContext.Session.GetString("pal") == null)
     {
         Pal    pal     = new Pal();
         string jsonpal = JsonConvert.SerializeObject(pal);
         HttpContext.Session.SetString("pal", jsonpal);
         ViewBag.pal = pal;
     }
     else
     {
         string old = HttpContext.Session.GetString("pal");
         Pal    pal = JsonConvert.DeserializeObject <Pal>(old);
         ViewBag.pal = pal;
     }
     return(View("index"));
 }