Ejemplo n.º 1
0
 //convert from System.Runtime.InteropServices.ComTypes.FILETIME to the local System.DateTime
 // The COM FILETIME is based on coordinated universal time (UTC). UTC-based time is loosely defined as the current date and time of day in Greenwich, England.
 // this function uses the current system settings for the time zone (differenc from UTC to your timezone) and daylight saving time (summer- / winter-time settings).
 static DateTime ConvertFromFILETIME(System.Runtime.InteropServices.ComTypes.FILETIME FileTime)
 {
     long highBits = FileTime.dwHighDateTime;
     highBits = highBits << 32;
     try { return DateTime.FromFileTimeUtc(highBits | (long)(uint)FileTime.dwLowDateTime).ToLocalTime(); }
     catch { return DateTime.MinValue; }
 }
Ejemplo n.º 2
0
        private int CpuUsage(ComType.FILETIME newKernelTime, ComType.FILETIME newUserTime, ComType.FILETIME newProcessKernelTime, ComType.FILETIME newProcessUserTime)
        {
            int rawUsage;

            ulong processKernelTime = SubtractTimes(newProcessKernelTime, oldProcessKernelTime);
            ulong processUserTime   = SubtractTimes(newProcessUserTime, oldProcessUserTime);


            ulong kernelTime = SubtractTimes(newKernelTime, oldKernelTime);
            ulong userTime   = SubtractTimes(newUserTime, oldUserTime);

            double processTotal = processUserTime + processKernelTime;
            double systemTotal  = userTime + kernelTime;

            if (systemTotal <= double.Epsilon)
            {
                return(-1);
            }
            double division = processTotal / systemTotal;

            rawUsage = Mathf.RoundToInt((float)division * 100f);

            oldUserTime          = newUserTime;
            oldKernelTime        = newKernelTime;
            oldProcessKernelTime = newProcessKernelTime;
            oldProcessUserTime   = newProcessUserTime;

            return(rawUsage);
        }
Ejemplo n.º 3
0
        private Int64 SubtractTimes(ct.FILETIME a, ct.FILETIME b)
        {
            Int64 aInt = ((Int64)(a.dwHighDateTime << 32)) | (Int64)a.dwLowDateTime;
            Int64 bInt = ((Int64)(b.dwHighDateTime << 32)) | (Int64)b.dwLowDateTime;

            return(aInt - bInt);
        }
Ejemplo n.º 4
0
        private UInt64 SubtractTimes(ComTypes.FILETIME a, ComTypes.FILETIME b)
        {
            UInt64 aInt = ((UInt64)(a.dwHighDateTime << 32)) | (UInt64)a.dwLowDateTime;
            UInt64 bInt = ((UInt64)(b.dwHighDateTime << 32)) | (UInt64)b.dwLowDateTime;

            return(aInt - bInt);
        }
Ejemplo n.º 5
0
        private ulong SubtractTimes(ComType.FILETIME a, ComType.FILETIME b)
        {
            DateTime adate = ToDateTime(a);
            DateTime bdate = ToDateTime(b);

            return((ulong)(adate.Ticks - bdate.Ticks));
        }
Ejemplo n.º 6
0
		public int GetLastSyncTime(out FILETIME pftLastSync)
		{
			pftLastSync = new FILETIME();
			pftLastSync.dwHighDateTime = 0;
			pftLastSync.dwLowDateTime = 0;
			return 0;
		}
 internal static OpcDaItemValue[] Create(OpcDaGroup opcDaGroup, int dwCount, int[] phClientItems,
     object[] pvValues,
     short[] pwQualities, FILETIME[] pftTimeStamps, HRESULT[] pErrors)
 {
     try
     {
         var values = new OpcDaItemValue[dwCount];
         for (var i = 0; i < values.Length; i++)
         {
             values[i] = new OpcDaItemValue
             {
                 Value = pvValues[i],
                 Item = opcDaGroup.GetItem(phClientItems[i]),
                 Quality = pwQualities[i],
                 Timestamp = FileTimeConverter.FromFileTime(pftTimeStamps[i]),
                 Error = pErrors[i]
             };
         }
         return values;
     }
     catch (Exception ex)
     {
         Log.Error("Cannot create OpcDaItemValue object.", ex);
         return new OpcDaItemValue[0];
     }
 }
Ejemplo n.º 8
0
        IEnumerator KeepTracking()
        {
            ComType.FILETIME idleTime, kernelTime, userTime, processCreationTime, processExitTime, processKernelTime, processUserTime;
            while (!GetSystemTimes(out idleTime, out kernelTime, out userTime) ||
                   !GetProcessTimes(currentProcessHandle, out processCreationTime, out processExitTime, out processKernelTime, out processUserTime))
            {
                yield return(null);
            }
            oldKernelTime        = kernelTime;
            oldUserTime          = userTime;
            oldProcessKernelTime = processKernelTime;
            oldProcessUserTime   = processUserTime;

            while (true)
            {
                if (IsTracking)
                {
                    yield return(timeInterval);

                    if (GetSystemTimes(out idleTime, out kernelTime, out userTime) &&
                        GetProcessTimes(currentProcessHandle, out processCreationTime, out processExitTime, out processKernelTime, out processUserTime))
                    {
                        int value = CpuUsage(kernelTime, userTime, processKernelTime, processUserTime);

                        SetCurrent(value);
                    }
                }
                else
                {
                    yield return(null);
                }
            }
        }
Ejemplo n.º 9
0
 private static System.Runtime.InteropServices.ComTypes.FILETIME GetFILETIME(long time)
 {
     System.Runtime.InteropServices.ComTypes.FILETIME fileTime = new System.Runtime.InteropServices.ComTypes.FILETIME();
     fileTime.dwLowDateTime  = (int)time;
     fileTime.dwHighDateTime = (int)(time >> 0x20);
     return(fileTime);
 }
Ejemplo n.º 10
0
        public static int CmpFileTimes(System.Runtime.InteropServices.ComTypes.FILETIME a, System.Runtime.InteropServices.ComTypes.FILETIME b)
        {
            long aLong = Misc.FiletimeToLong(a);
            long bLong = Misc.FiletimeToLong(b);

            return(CompareULongsToInt((ulong)aLong, (ulong)bLong));
        }
Ejemplo n.º 11
0
        public double get_cpu_instant()
        {
            double cpuCopy = _cpuUsage;

            if (EnoughTimePassed())
            {
                ComTypes.FILETIME sysIdle, sysKernel, sysUser;
                TimeSpan          procTime;

                Process process = Process.GetCurrentProcess();
                procTime = process.TotalProcessorTime;

                if (GetSystemTimes(out sysIdle, out sysKernel, out sysUser))
                {
                    UInt64 sysKernelDiff = SubtractTimes(
                        sysKernel, _prevSysKernel);
                    UInt64 sysUserDiff = SubtractTimes(sysUser, _prevSysUser);
                    UInt64 sysTotal    = sysKernelDiff + sysUserDiff;
                    Int64  procTotal   = procTime.Ticks - _prevProcTotal.Ticks;
                    if (sysTotal > 0)
                    {
                        _cpuUsage = (double)((100.0 * procTotal) / sysTotal);
                    }
                    _prevProcTotal = procTime;
                    _prevSysKernel = sysKernel;
                    _prevSysUser   = sysUser;
                    _lastRun       = DateTime.Now;
                    cpuCopy        = _cpuUsage;
                }
            }
            _cpuUsageTotal += cpuCopy;
            _counter++;
            return(cpuCopy);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Determine the current CPU usage in percent
        /// </summary>
        /// <param name="WorkingSet">The working set</param>
        /// <param name="memStatus"></param>
        /// <returns></returns>
        public static short GetCPUUsage(out long WorkingSet, out MEMORYSTATUSEX memStatus)
        {
            short cpuCopy = _cpuUsage;

            if (Interlocked.Increment(ref _runCount) == 1)
            {
                if (!EnoughTimePassed)
                {
                    Interlocked.Decrement(ref _runCount);
                    WorkingSet = _lastWorkingSet;
                    memStatus  = _lastmemStatus;
                    return(cpuCopy);
                }

                ComTypes.FILETIME sysIdle, sysKernel, sysUser;
                TimeSpan          procTime;

                using (Process process = Process.GetCurrentProcess())
                {
                    procTime   = process.TotalProcessorTime;
                    WorkingSet = _lastWorkingSet = process.WorkingSet64;
                    memStatus  = _lastmemStatus = new MEMORYSTATUSEX();
                    GlobalMemoryStatusEx(memStatus);
                }

                if (!GetSystemTimes(out sysIdle, out sysKernel, out sysUser))
                {
                    Interlocked.Decrement(ref _runCount);
                    WorkingSet = _lastWorkingSet;
                    return(cpuCopy);
                }

                if (!IsFirstRun)
                {
                    UInt64 sysKernelDiff = SubtractTimes(sysKernel, _prevSysKernel);
                    UInt64 sysUserDiff   = SubtractTimes(sysUser, _prevSysUser);
                    UInt64 sysTotal      = sysKernelDiff + sysUserDiff;
                    Int64  procTotal     = procTime.Ticks - _prevProcTotal.Ticks;
                    if (sysTotal > 0)
                    {
                        _cpuUsage = (short)((100.0 * procTotal) / sysTotal);
                    }
                }

                _prevProcTotal = procTime;
                _prevSysKernel = sysKernel;
                _prevSysUser   = sysUser;
                _lastRun       = DateTime.Now;
                cpuCopy        = _cpuUsage;
            }
            else
            {
                WorkingSet = _lastWorkingSet;
                memStatus  = _lastmemStatus;
            }


            Interlocked.Decrement(ref _runCount);
            return(cpuCopy);
        }
Ejemplo n.º 13
0
        public OpcDaVQTE[] Read(IList<string> itemIds, IList<TimeSpan> maxAge)
        {
            if (maxAge == null)
                maxAge = new TimeSpan[itemIds.Count];
            if (itemIds.Count != maxAge.Count)
                throw new ArgumentException("Invalid size of maxAge", "maxAge");

            int[] intMaxAge = ArrayHelpers.CreateMaxAgeArray(maxAge, itemIds.Count);

            string[] pszItemIDs = itemIds.ToArray();
            var ppvValues = new object[pszItemIDs.Length];
            var ppwQualities = new short[pszItemIDs.Length];
            var ppftTimeStamps = new FILETIME[pszItemIDs.Length];
            var ppErrors = new HRESULT[pszItemIDs.Length];
            DoComCall(ComObject, "IOPCItemIO::Read", () =>
                    ComObject.Read(pszItemIDs.Length, pszItemIDs, intMaxAge, out ppvValues, out ppwQualities,
                        out ppftTimeStamps, out ppErrors), pszItemIDs.Length, pszItemIDs,
                maxAge);

            var result = new OpcDaVQTE[itemIds.Count];
            for (int i = 0; i < ppvValues.Length; i++)
            {
                var vqte = new OpcDaVQTE
                {
                    Value = ppvValues[i],
                    Quality = ppwQualities[i],
                    Timestamp = FileTimeConverter.FromFileTime(ppftTimeStamps[i]),
                    Error = ppErrors[i]
                };
                result[i] = vqte;
            }
            return result;
        }
        private static UInt64 SubtractTimes(ComTypes.FILETIME a, ComTypes.FILETIME b)
        {
            var aInt = ((UInt64)(a.dwHighDateTime << 32)) | (UInt64)a.dwLowDateTime;
            var bInt = ((UInt64)(b.dwHighDateTime << 32)) | (UInt64)b.dwLowDateTime;

            return(aInt - bInt);
        }
Ejemplo n.º 15
0
            private ulong SubtractTimes(System.Runtime.InteropServices.ComTypes.FILETIME a, System.Runtime.InteropServices.ComTypes.FILETIME b)
            {
                ulong num  = (ulong)(a.dwHighDateTime | a.dwLowDateTime);
                ulong num2 = (ulong)(b.dwHighDateTime | b.dwLowDateTime);

                return(num - num2);
            }
Ejemplo n.º 16
0
        private string GetFileTimeString(string fileName)
        {
            int hFile = 0;

            try
            {
                SECURITY_ATTRIBUTES a = new SECURITY_ATTRIBUTES();
                hFile = CreateFileA(fileName, (uint)0x80000000, 0x1 | 0x2, ref a, 0x3, 0, 0);
                if (hFile != 0)
                {
                    System.Runtime.InteropServices.ComTypes.FILETIME ftCreate     = new System.Runtime.InteropServices.ComTypes.FILETIME();
                    System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccess = new System.Runtime.InteropServices.ComTypes.FILETIME();
                    System.Runtime.InteropServices.ComTypes.FILETIME ftLastWrite  = new System.Runtime.InteropServices.ComTypes.FILETIME();
                    int ret = GetFileTime(hFile, ref ftCreate, ref ftLastAccess, ref ftLastWrite);
                    return(ftCreate.dwHighDateTime.ToString() + "_" + ftCreate.dwLowDateTime.ToString());
                }
                else
                {
                    return(fileName);
                }
            }
            catch (Exception err)
            {
                return(fileName + "_" + err.ToString());
            }
            finally
            {
                if (hFile != 0)
                {
                    CloseHandle(hFile);
                }
            }
        }
Ejemplo n.º 17
0
 public static ComTypes.FILETIME DateTimeToFileTime(long d)
 {
     ComTypes.FILETIME ft = new ComTypes.FILETIME();
     ft.dwHighDateTime = (int)(d >> 32);
     ft.dwLowDateTime  = (int)(d & 0xffffffff);
     return(ft);
 }
Ejemplo n.º 18
0
        UInt64 SubtractTimes(System.Runtime.InteropServices.ComTypes.FILETIME a, ComTypes.FILETIME b)
        {
            UInt64 aInt = ((UInt64)(a.dwHighDateTime << 32) | (UInt64)a.dwLowDateTime);
            UInt64 bInt = ((UInt64)(b.dwHighDateTime << 32) | (UInt64)b.dwLowDateTime);

            return(aInt - bInt);
        }
        public static Stream CreateFileGroupDescriptorW(string fileName, DateTimeOffset lastWriteTime)
        {
            var fileGroupDescriptor = new FILEGROUPDESCRIPTORW()
            {
                cItems = 1
            };
            var fileDescriptor = new FILEDESCRIPTORW()
            {
                cFileName = fileName
            };

            fileDescriptor.dwFlags |= FD_SHOWPROGRESSUI;

            fileDescriptor.dwFlags |= FD_CREATETIME | FD_WRITESTIME;
            var changeTime         = lastWriteTime.ToLocalTime().ToFileTime();
            var changeTimeFileTime = new System.Runtime.InteropServices.ComTypes.FILETIME
            {
                dwLowDateTime  = (int)(changeTime & 0xffffffff),
                dwHighDateTime = (int)(changeTime >> 32),
            };

            fileDescriptor.ftLastWriteTime = changeTimeFileTime;
            fileDescriptor.ftCreationTime  = changeTimeFileTime;

            var fileGroupDescriptorBytes = StructureBytes(fileGroupDescriptor);
            var fileDescriptorBytes      = StructureBytes(fileDescriptor);

            var memoryStream = new MemoryStream();

            memoryStream.Write(fileGroupDescriptorBytes, 0, fileGroupDescriptorBytes.Length);
            memoryStream.Write(fileDescriptorBytes, 0, fileDescriptorBytes.Length);

            return(memoryStream);
        }
Ejemplo n.º 20
0
 //convert from System.DateTime to System.Runtime.InteropServices.ComTypes.FILETIME
 static System.Runtime.InteropServices.ComTypes.FILETIME ConvertToFILETIME(DateTime TimeAndDate)
 {
     System.Runtime.InteropServices.ComTypes.FILETIME FileTime = new System.Runtime.InteropServices.ComTypes.FILETIME();
     long dtFileTime = TimeAndDate.ToFileTime();
     FileTime.dwLowDateTime = (int)(dtFileTime & 0xFFFFFFFF);
     FileTime.dwHighDateTime = (int)(dtFileTime >> 32);
     return FileTime;
 }
Ejemplo n.º 21
0
 public static extern bool VBCreateFileTime(UInt16 Year,
                                            UInt16 Month,
                                            UInt16 Day,
                                            UInt16 Hour,
                                            UInt16 Minute,
                                            UInt16 Second,
                                            UInt16 Milliseconds,
                                            ref System.Runtime.InteropServices.ComTypes.FILETIME FileTime);
Ejemplo n.º 22
0
        public static void FileTimeToV8time(System.Runtime.InteropServices.ComTypes.FILETIME ft, ref Int64 v8t)
        {
            DateTime dateTime = ft.ToDateTime();

            v8t  = dateTime.Ticks;
            v8t /= 1000;
            v8t += DeltaData1C;
        }
Ejemplo n.º 23
0
        private static System.Runtime.InteropServices.ComTypes.FILETIME DateTimeToFileTime(DateTime value)
        {
            long hFT = value.ToFileTime();
            var  ft  = new System.Runtime.InteropServices.ComTypes.FILETIME();

            ft.dwLowDateTime  = (int)(hFT & 0xFFFFFFFFU);
            ft.dwHighDateTime = (int)(hFT >> 32);
            return(ft);
        }
Ejemplo n.º 24
0
 public int SetFileTime(IntPtr rawFilename, ref ComTypes.FILETIME rawCreationTime, ref ComTypes.FILETIME rawLastAccessTime, ref ComTypes.FILETIME rawLastWriteTime, ref FuserDefinition.FUSER_FILE_INFO rawHFile)
 {
     try {
         return(ConvReturnCodeToInt(this.fsDevice.SetFileTime(this.hManager.GetFileHandler(GetFilename(rawFilename), ref rawHFile), ConvDateTimeFromRAW(rawCreationTime), ConvDateTimeFromRAW(rawLastAccessTime), ConvDateTimeFromRAW(rawLastWriteTime))));
     } catch (Exception e) {
         this.fsDevice.LogErrorMessage("SetFileTime", e.Message);
         return(ConvReturnCodeToInt(Win32Returncode.DEFAULT_UNKNOWN_ERROR));
     }
 }
Ejemplo n.º 25
0
        public double GetUsage()
        {
            double cpuCopy = _cpuUsage;

            if (Interlocked.Increment(ref _runCount) == 1)
            {
                if (!EnoughTimePassed)
                {
                    Interlocked.Decrement(ref _runCount);
                    return(cpuCopy);
                }

                ComTypes.FILETIME sysIdle, sysKernel, sysUser;
                TimeSpan          procTime;

                Process process = Process.GetCurrentProcess();

                if (process == null)
                {
                    return(-1);
                }

                procTime = process.TotalProcessorTime;


                if (!GetSystemTimes(out sysIdle, out sysKernel, out sysUser))
                {
                    Interlocked.Decrement(ref _runCount);
                    return(cpuCopy);
                }

                if (!IsFirstRun)
                {
                    UInt64 sysKernelDiff = SubtractTimes(sysKernel, _prevSysKernel);
                    UInt64 sysUserDiff   = SubtractTimes(sysUser, _prevSysUser);

                    UInt64 sysTotal = sysKernelDiff + sysUserDiff;

                    Int64 procTotal = procTime.Ticks - _prevProcTotal.Ticks;

                    if (sysTotal > 0)
                    {
                        _cpuUsage = ((100.0 * procTotal) / sysTotal);
                    }
                }

                _prevProcTotal = procTime;
                _prevSysKernel = sysKernel;
                _prevSysUser   = sysUser;

                _lastRun = DateTime.Now;

                cpuCopy = _cpuUsage;
            }
            Interlocked.Decrement(ref _runCount);
            return(cpuCopy);
        }
Ejemplo n.º 26
0
 private static unsafe int FindTimeValidCallback(System.Security.Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData)
 {
     System.Runtime.InteropServices.ComTypes.FILETIME pTimeToVerify = (System.Runtime.InteropServices.ComTypes.FILETIME)pvCallbackData;
     CAPIBase.CERT_CONTEXT cert_context = *((CAPIBase.CERT_CONTEXT *)safeCertContextHandle.DangerousGetHandle());
     if (CAPISafe.CertVerifyTimeValidity(ref pTimeToVerify, cert_context.pCertInfo) == 0)
     {
         return(0);
     }
     return(1);
 }
Ejemplo n.º 27
0
        public static void V8timeToFileTime(Int64 v8t, ref System.Runtime.InteropServices.ComTypes.FILETIME ft)
        {
            Int64 t = v8t;

            t -= DeltaData1C;
            t *= 1000;
            DateTime dateTime = new DateTime(t);

            ft = DateTimeToFILETIME(dateTime);
        }
Ejemplo n.º 28
0
        private static DateTime SystemTimeToDateTime(ref SYSTEMTIME st)
        {
            System.Runtime.InteropServices.ComTypes.FILETIME ft = new System.Runtime.InteropServices.ComTypes.FILETIME();

            NativeMethods.SystemTimeToFileTime(ref st, out ft);

            DateTime dt = new DateTime((((long)ft.dwHighDateTime) << 32) | (uint)ft.dwLowDateTime);

            return(dt);
        }
Ejemplo n.º 29
0
        public void initialize()
        {
            _lastRun = DateTime.Now;
            Process process = Process.GetCurrentProcess();

            _prevProcTotal = process.TotalProcessorTime;
            ComTypes.FILETIME sysIdle, sysKernel, sysUser;
            GetSystemTimes(out sysIdle, out sysKernel, out sysUser);
            _prevSysKernel = sysKernel;
            _prevSysUser   = sysUser;
        }
        public int GetDateStamp([In, Out] ref System.Runtime.InteropServices.ComTypes.FILETIME pDateStamp)
        {
            WriteLine("tlogThumbnailHandler GetDateStamp");
            FileInfo fi = new FileInfo(m_filename);

            pDateStamp = new System.Runtime.InteropServices.ComTypes.FILETIME();
            pDateStamp.dwLowDateTime  = (int)fi.LastWriteTime.ToFileTime();
            pDateStamp.dwHighDateTime = (int)(fi.LastWriteTime.ToFileTime() >> 32);

            return((int)S_OK);
        }
        /// <summary>
        /// Provides data for the specified data format (FILEGROUPDESCRIPTOR/FILEDESCRIPTOR)
        /// </summary>
        /// <param name="fileDescriptors">Collection of virtual files.</param>
        public void SetData(IEnumerable <FileDescriptor> fileDescriptors)
        {
            // Prepare buffer
            var bytes = new List <byte>();

            // Add FILEGROUPDESCRIPTOR header
            bytes.AddRange(StructureBytes(new NativeMethods.FILEGROUPDESCRIPTOR {
                cItems = (uint)(fileDescriptors.Count())
            }));
            // Add n FILEDESCRIPTORs
            foreach (var fileDescriptor in fileDescriptors)
            {
                // Set required fields
                var FILEDESCRIPTOR = new NativeMethods.FILEDESCRIPTOR
                {
                    cFileName = fileDescriptor.Name,
                };
                // Set optional timestamp
                if (fileDescriptor.ChangeTimeUtc.HasValue)
                {
                    FILEDESCRIPTOR.dwFlags |= NativeMethods.FD_CREATETIME | NativeMethods.FD_WRITESTIME;
                    var changeTime         = fileDescriptor.ChangeTimeUtc.Value.ToLocalTime().ToFileTime();
                    var changeTimeFileTime = new System.Runtime.InteropServices.ComTypes.FILETIME
                    {
                        dwLowDateTime  = (int)(changeTime & 0xffffffff),
                        dwHighDateTime = (int)(changeTime >> 32),
                    };
                    FILEDESCRIPTOR.ftLastWriteTime = changeTimeFileTime;
                    FILEDESCRIPTOR.ftCreationTime  = changeTimeFileTime;
                }
                // Set optional length
                if (fileDescriptor.Length.HasValue)
                {
                    FILEDESCRIPTOR.dwFlags      |= NativeMethods.FD_FILESIZE;
                    FILEDESCRIPTOR.nFileSizeLow  = (uint)(fileDescriptor.Length & 0xffffffff);
                    FILEDESCRIPTOR.nFileSizeHigh = (uint)(fileDescriptor.Length >> 32);
                }
                // Add structure to buffer
                bytes.AddRange(StructureBytes(FILEDESCRIPTOR));
            }

            // Set CFSTR_FILEDESCRIPTORW
            SetData(FILEDESCRIPTORW, bytes);
            // Set n CFSTR_FILECONTENTS
            var index = 0;

            foreach (var fileDescriptor in fileDescriptors)
            {
                SetData(FILECONTENTS, index, fileDescriptor.StreamContents);
                index++;
            }
        }
Ejemplo n.º 32
0
        private static SYSTEMTIME DateTimeToSystemTime(DateTime dt)
        {
            SYSTEMTIME st;

            System.Runtime.InteropServices.ComTypes.FILETIME ft = new System.Runtime.InteropServices.ComTypes.FILETIME();

            ft.dwHighDateTime = (int)(dt.Ticks >> 32);
            ft.dwLowDateTime  = (int)(dt.Ticks & 0xFFFFFFFFL);

            NativeMethods.FileTimeToSystemTime(ref ft, out st);

            return(st);
        }
Ejemplo n.º 33
0
        public static bool SetFileTime(IntPtr hFile, System.Runtime.InteropServices.ComTypes.FILETIME lpCreationTime, System.Runtime.InteropServices.ComTypes.FILETIME lpLastAccessTime, System.Runtime.InteropServices.ComTypes.FILETIME lpLastWriteTime)
        {
            long c = Spi.Misc.FiletimeToLong(lpCreationTime);

            long a = Spi.Misc.FiletimeToLong(lpLastAccessTime);
            long w = Spi.Misc.FiletimeToLong(lpLastWriteTime);

            return
                (SetFileTime(
                     hFile: hFile,
                     lpCreationTime:     ref c,
                     lpLastAccessTime:   ref a,
                     lpLastWriteTime:    ref w));
        }
Ejemplo n.º 34
0
        internal static SensorReport FromNativeReport( Sensor originator, ISensorDataReport iReport )
        {
            SYSTEMTIME systemTimeStamp = new SYSTEMTIME( );
            iReport.GetTimestamp( out systemTimeStamp );
            FILETIME ftTimeStamp = new FILETIME( );
            SensorNativeMethods.SystemTimeToFileTime( ref systemTimeStamp, out ftTimeStamp );
            long lTimeStamp = (((long)ftTimeStamp.dwHighDateTime) << 32) + (long)ftTimeStamp.dwLowDateTime;
            DateTime timeStamp = DateTime.FromFileTime( lTimeStamp );

            SensorReport sensorReport = new SensorReport( );
            sensorReport.originator = originator;
            sensorReport.timeStamp = timeStamp;
            sensorReport.sensorData = SensorData.FromNativeReport( originator.internalObject, iReport );

            return sensorReport;
        }
Ejemplo n.º 35
0
		public short GetUsage()
		{
			short cpuCopy = _cpuUsage;
			if (Interlocked.Increment(ref _runCount) == 1) {
				if (!EnoughTimePassed) {
					Interlocked.Decrement(ref _runCount);
					return cpuCopy;
				}

				ComTypes.FILETIME sysIdle, sysKernel, sysUser;
				TimeSpan procTime;

				Process process = Process.GetCurrentProcess();
				procTime = process.TotalProcessorTime;

				if (!GetSystemTimes(out sysIdle, out sysKernel, out sysUser)) {
					Interlocked.Decrement(ref _runCount);
					return cpuCopy;
				}

				if (!IsFirstRun) {
					UInt64 sysKernelDiff = SubtractTimes(sysKernel, _prevSysKernel);
					UInt64 sysUserDiff = SubtractTimes(sysUser, _prevSysUser);

					UInt64 sysTotal = sysKernelDiff + sysUserDiff;

					Int64 procTotal = procTime.Ticks - _prevProcTotal.Ticks;

					if (sysTotal > 0) {
						_cpuUsage = (short) ((100.0*procTotal)/sysTotal);
					}
				}

				_prevProcTotal = procTime;
				_prevSysKernel = sysKernel;
				_prevSysUser = sysUser;

				_lastRun = DateTime.Now;

				cpuCopy = _cpuUsage;
			}
			Interlocked.Decrement(ref _runCount);

			return cpuCopy;
		}
        private void OnDataChange(int dwTransid, int hGroup, HRESULT hrMasterquality, HRESULT hrMastererror,
            int dwCount, int[] phClientItems,
            object[] pvValues, short[] pwQualities, FILETIME[] pftTimeStamps, HRESULT[] pErrors)
        {
            try
            {
                Log.TraceFormat(
                    "On data change. Transaction id: {0}. Client group handle: {1}. Master quality: {2}. Error: {3}.",
                    dwTransid, hGroup, hrMasterquality, hrMastererror);
                if (hGroup != _opcDaGroup.ClientHandle)
                    throw new ArgumentException("Wrong group handle", "hGroup");

                OpcDaItemValue[] values = OpcDaItemValue.Create(_opcDaGroup, dwCount, phClientItems, pvValues,
                    pwQualities,
                    pftTimeStamps, pErrors);
                if (dwTransid == 0) // Data from subscription
                {
                    OnNewItemValues(values);
                    return;
                }

                IAsyncRequest request = CompleteRequest(dwTransid);
                if (request == null)
                    return;

                if (request.TransactionId != dwTransid)
                    throw new ArgumentException("Wrong transaction id.", "dwTransid");

                request.OnDataChange(dwTransid, hGroup, hrMasterquality, hrMastererror, values);
                OnNewItemValues(values);
            }
            catch (Exception ex)
            {
                Log.Error("Error on data change.", ex);
            }
        }
 internal static unsafe int BuildChain(IntPtr hChainEngine, System.Security.Cryptography.SafeCertContextHandle pCertContext, X509Certificate2Collection extraStore, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, TimeSpan timeout, ref SafeCertChainHandle ppChainContext)
 {
     CAPIBase.CERT_CHAIN_PARA cert_chain_para;
     if ((pCertContext == null) || pCertContext.IsInvalid)
     {
         throw new ArgumentException(SR.GetString("Cryptography_InvalidContextHandle"), "pCertContext");
     }
     System.Security.Cryptography.SafeCertStoreHandle invalidHandle = System.Security.Cryptography.SafeCertStoreHandle.InvalidHandle;
     if ((extraStore != null) && (extraStore.Count > 0))
     {
         invalidHandle = System.Security.Cryptography.X509Certificates.X509Utils.ExportToMemoryStore(extraStore);
     }
     cert_chain_para = new CAPIBase.CERT_CHAIN_PARA {
         cbSize = (uint) Marshal.SizeOf(cert_chain_para)
     };
     SafeLocalAllocHandle handle2 = SafeLocalAllocHandle.InvalidHandle;
     if ((applicationPolicy != null) && (applicationPolicy.Count > 0))
     {
         cert_chain_para.RequestedUsage.dwType = 0;
         cert_chain_para.RequestedUsage.Usage.cUsageIdentifier = (uint) applicationPolicy.Count;
         handle2 = System.Security.Cryptography.X509Certificates.X509Utils.CopyOidsToUnmanagedMemory(applicationPolicy);
         cert_chain_para.RequestedUsage.Usage.rgpszUsageIdentifier = handle2.DangerousGetHandle();
     }
     SafeLocalAllocHandle handle3 = SafeLocalAllocHandle.InvalidHandle;
     if ((certificatePolicy != null) && (certificatePolicy.Count > 0))
     {
         cert_chain_para.RequestedIssuancePolicy.dwType = 0;
         cert_chain_para.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint) certificatePolicy.Count;
         handle3 = System.Security.Cryptography.X509Certificates.X509Utils.CopyOidsToUnmanagedMemory(certificatePolicy);
         cert_chain_para.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = handle3.DangerousGetHandle();
     }
     cert_chain_para.dwUrlRetrievalTimeout = (uint) timeout.Milliseconds;
     System.Runtime.InteropServices.ComTypes.FILETIME pTime = new System.Runtime.InteropServices.ComTypes.FILETIME();
     *((long*) &pTime) = verificationTime.ToFileTime();
     uint dwFlags = System.Security.Cryptography.X509Certificates.X509Utils.MapRevocationFlags(revocationMode, revocationFlag);
     if (!CAPISafe.CertGetCertificateChain(hChainEngine, pCertContext, ref pTime, invalidHandle, ref cert_chain_para, dwFlags, IntPtr.Zero, ref ppChainContext))
     {
         return Marshal.GetHRForLastWin32Error();
     }
     handle2.Dispose();
     handle3.Dispose();
     return 0;
 }
Ejemplo n.º 38
0
 public virtual extern HRESULT GetDate(string pszPropertyName, uint dwFlags, out FILETIME pftDateTime);
Ejemplo n.º 39
0
		public override void SendAdvise_DataChanged()
		{
			base.SendAdvise_DataChanged();

			// we must also note the change time to the running object table, see
			// Brockschmidt, Inside Ole 2nd ed., page 989
			var rotCookie = _documentMonikerRotCookie;
			if (rotCookie != 0)
			{
				System.Runtime.InteropServices.ComTypes.FILETIME ft = new System.Runtime.InteropServices.ComTypes.FILETIME();
				Ole32Func.CoFileTimeNow(out ft);
				RunningObjectTableHelper.GetROT().NoteChangeTime(rotCookie, ref ft);
			}
		}
 private static unsafe void BuildChain(IntPtr hChainEngine, IntPtr pCertContext, X509Certificate2Collection extraStore, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, TimeSpan timeout, out System.IdentityModel.SafeCertChainHandle ppChainContext)
 {
     System.IdentityModel.SafeCertStoreHandle hAdditionalStore = ExportToMemoryStore(extraStore, pCertContext);
     System.IdentityModel.CAPI.CERT_CHAIN_PARA pChainPara = new System.IdentityModel.CAPI.CERT_CHAIN_PARA {
         cbSize = (uint) Marshal.SizeOf(typeof(System.IdentityModel.CAPI.CERT_CHAIN_PARA))
     };
     SafeHGlobalHandle invalidHandle = SafeHGlobalHandle.InvalidHandle;
     SafeHGlobalHandle handle3 = SafeHGlobalHandle.InvalidHandle;
     try
     {
         if ((applicationPolicy != null) && (applicationPolicy.Count > 0))
         {
             pChainPara.RequestedUsage.dwType = 0;
             pChainPara.RequestedUsage.Usage.cUsageIdentifier = (uint) applicationPolicy.Count;
             invalidHandle = CopyOidsToUnmanagedMemory(applicationPolicy);
             pChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = invalidHandle.DangerousGetHandle();
         }
         if ((certificatePolicy != null) && (certificatePolicy.Count > 0))
         {
             pChainPara.RequestedIssuancePolicy.dwType = 0;
             pChainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint) certificatePolicy.Count;
             handle3 = CopyOidsToUnmanagedMemory(certificatePolicy);
             pChainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = handle3.DangerousGetHandle();
         }
         pChainPara.dwUrlRetrievalTimeout = (uint) timeout.Milliseconds;
         System.Runtime.InteropServices.ComTypes.FILETIME pTime = new System.Runtime.InteropServices.ComTypes.FILETIME();
         *((long*) &pTime) = verificationTime.ToFileTime();
         uint dwFlags = MapRevocationFlags(revocationMode, revocationFlag);
         if (!System.IdentityModel.CAPI.CertGetCertificateChain(hChainEngine, pCertContext, ref pTime, hAdditionalStore, ref pChainPara, dwFlags, IntPtr.Zero, out ppChainContext))
         {
             int hr = Marshal.GetLastWin32Error();
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(hr));
         }
     }
     finally
     {
         if (invalidHandle != null)
         {
             invalidHandle.Dispose();
         }
         if (handle3 != null)
         {
             handle3.Dispose();
         }
         hAdditionalStore.Close();
     }
 }
        private unsafe static Cryptography.SafeCertStoreHandle FindCertInStore(Cryptography.SafeCertStoreHandle safeSourceStoreHandle, X509FindType findType, Object findValue, bool validOnly) {
            if (findValue == null)
                throw new ArgumentNullException("findValue");

            IntPtr pvFindPara = IntPtr.Zero;
            object pvCallbackData1 = null;
            object pvCallbackData2 = null;
            FindProcDelegate pfnCertCallback1 = null;
            FindProcDelegate pfnCertCallback2 = null;
            uint dwFindType = CAPI.CERT_FIND_ANY;
            string subject, issuer;

            CAPI.CRYPTOAPI_BLOB HashBlob = new CAPI.CRYPTOAPI_BLOB();
            SafeLocalAllocHandle pb = SafeLocalAllocHandle.InvalidHandle;
            _FILETIME ft = new _FILETIME();
            string oidValue = null;

            switch(findType) {
            case X509FindType.FindByThumbprint:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                byte[] hex = X509Utils.DecodeHexString((string) findValue);
                pb = X509Utils.ByteToPtr(hex);
                HashBlob.pbData = pb.DangerousGetHandle(); 
                HashBlob.cbData = (uint) hex.Length;
                dwFindType = CAPI.CERT_FIND_HASH;
                pvFindPara = new IntPtr(&HashBlob);
                break;

            case X509FindType.FindBySubjectName:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                subject = (string) findValue;
                dwFindType = CAPI.CERT_FIND_SUBJECT_STR;
                pb = X509Utils.StringToUniPtr(subject);
                pvFindPara = pb.DangerousGetHandle();
                break;

            case X509FindType.FindBySubjectDistinguishedName:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                subject = (string) findValue;
                pfnCertCallback1 = new FindProcDelegate(FindSubjectDistinguishedNameCallback);
                pvCallbackData1 = subject;
                break;

            case X509FindType.FindByIssuerName:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                issuer = (string) findValue;
                dwFindType = CAPI.CERT_FIND_ISSUER_STR;
                pb = X509Utils.StringToUniPtr(issuer);
                pvFindPara = pb.DangerousGetHandle();
                break;

            case X509FindType.FindByIssuerDistinguishedName:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                issuer = (string) findValue;
                pfnCertCallback1 = new FindProcDelegate(FindIssuerDistinguishedNameCallback);
                pvCallbackData1 = issuer;
                break;

            case X509FindType.FindBySerialNumber:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                pfnCertCallback1 = new FindProcDelegate(FindSerialNumberCallback);
                pfnCertCallback2 = new FindProcDelegate(FindSerialNumberCallback);
                BigInt h = new BigInt();
                h.FromHexadecimal((string) findValue);
                pvCallbackData1 = (byte[]) h.ToByteArray();
                h.FromDecimal((string) findValue);
                pvCallbackData2 = (byte[]) h.ToByteArray();
                break;

            case X509FindType.FindByTimeValid:
                if (findValue.GetType() != typeof(DateTime))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                *((long*) &ft) = ((DateTime) findValue).ToFileTime();
                pfnCertCallback1 = new FindProcDelegate(FindTimeValidCallback);
                pvCallbackData1 = ft; 
                break;

            case X509FindType.FindByTimeNotYetValid:
                if (findValue.GetType() != typeof(DateTime))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                *((long*) &ft) = ((DateTime) findValue).ToFileTime();
                pfnCertCallback1 = new FindProcDelegate(FindTimeNotBeforeCallback);
                pvCallbackData1 = ft; 
                break;

            case X509FindType.FindByTimeExpired:
                if (findValue.GetType() != typeof(DateTime))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                *((long*) &ft) = ((DateTime) findValue).ToFileTime();
                pfnCertCallback1 = new FindProcDelegate(FindTimeNotAfterCallback);
                pvCallbackData1 = ft; 
                break;

            case X509FindType.FindByTemplateName:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                pvCallbackData1 = (string) findValue; 
                pfnCertCallback1 = new FindProcDelegate(FindTemplateNameCallback);
                break;

            case X509FindType.FindByApplicationPolicy:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                // If we were passed the friendly name, retrieve the value string.
                oidValue = X509Utils.FindOidInfoWithFallback(CAPI.CRYPT_OID_INFO_NAME_KEY, (string) findValue, Cryptography.OidGroup.Policy);
                if (oidValue == null) {
                    oidValue = (string) findValue;
                    X509Utils.ValidateOidValue(oidValue);
                }
                pvCallbackData1 = oidValue;
                pfnCertCallback1 = new FindProcDelegate(FindApplicationPolicyCallback);
                break;

            case X509FindType.FindByCertificatePolicy:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                // If we were passed the friendly name, retrieve the value string.
                oidValue = X509Utils.FindOidInfoWithFallback(CAPI.CRYPT_OID_INFO_NAME_KEY, (string)findValue, Cryptography.OidGroup.Policy);
                if (oidValue == null) {
                    oidValue = (string) findValue;
                    X509Utils.ValidateOidValue(oidValue);
                }
                pvCallbackData1 = oidValue;
                pfnCertCallback1 = new FindProcDelegate(FindCertificatePolicyCallback);
                break;

            case X509FindType.FindByExtension:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                // If we were passed the friendly name, retrieve the value string.
                oidValue = X509Utils.FindOidInfoWithFallback(CAPI.CRYPT_OID_INFO_NAME_KEY, (string)findValue, Cryptography.OidGroup.ExtensionOrAttribute);
                if (oidValue == null) {
                    oidValue = (string) findValue;
                    X509Utils.ValidateOidValue(oidValue);
                }
                pvCallbackData1 = oidValue;
                pfnCertCallback1 = new FindProcDelegate(FindExtensionCallback);
                break;

            case X509FindType.FindByKeyUsage:
                // The findValue object can be either a friendly name, a X509KeyUsageFlags enum or an integer.
                if (findValue.GetType() == typeof(string)) {
                    CAPI.KEY_USAGE_STRUCT[] KeyUsages = new CAPI.KEY_USAGE_STRUCT[] { 
                        new CAPI.KEY_USAGE_STRUCT("DigitalSignature", CAPI.CERT_DIGITAL_SIGNATURE_KEY_USAGE),
                        new CAPI.KEY_USAGE_STRUCT("NonRepudiation",   CAPI.CERT_NON_REPUDIATION_KEY_USAGE),
                        new CAPI.KEY_USAGE_STRUCT("KeyEncipherment",  CAPI.CERT_KEY_ENCIPHERMENT_KEY_USAGE),
                        new CAPI.KEY_USAGE_STRUCT("DataEncipherment", CAPI.CERT_DATA_ENCIPHERMENT_KEY_USAGE),
                        new CAPI.KEY_USAGE_STRUCT("KeyAgreement",     CAPI.CERT_KEY_AGREEMENT_KEY_USAGE),
                        new CAPI.KEY_USAGE_STRUCT("KeyCertSign",      CAPI.CERT_KEY_CERT_SIGN_KEY_USAGE),
                        new CAPI.KEY_USAGE_STRUCT("CrlSign",          CAPI.CERT_CRL_SIGN_KEY_USAGE),
                        new CAPI.KEY_USAGE_STRUCT("EncipherOnly",     CAPI.CERT_ENCIPHER_ONLY_KEY_USAGE),
                        new CAPI.KEY_USAGE_STRUCT("DecipherOnly",     CAPI.CERT_DECIPHER_ONLY_KEY_USAGE)
                    };

                    for (uint index = 0; index < KeyUsages.Length; index++) {
                        if (String.Compare(KeyUsages[index].pwszKeyUsage, (string) findValue, StringComparison.OrdinalIgnoreCase) == 0) {
                            pvCallbackData1 = KeyUsages[index].dwKeyUsageBit;
                            break;
                        }
                    }
                    if (pvCallbackData1 == null)
                        throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindType));
                } else if (findValue.GetType() == typeof(X509KeyUsageFlags)) {
                    pvCallbackData1 = findValue;
                } else if (findValue.GetType() == typeof(uint) || findValue.GetType() == typeof(int)) {
                    // We got the actual DWORD
                    pvCallbackData1 = findValue;
                } else 
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindType));

                pfnCertCallback1 = new FindProcDelegate(FindKeyUsageCallback);
                break;

            case X509FindType.FindBySubjectKeyIdentifier:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                pvCallbackData1 = (byte[]) X509Utils.DecodeHexString((string) findValue);
                pfnCertCallback1 = new FindProcDelegate(FindSubjectKeyIdentifierCallback);
                break;

            default:
                throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindType));
            }

            // First, create a memory store
            Cryptography.SafeCertStoreHandle safeTargetStoreHandle = CAPI.CertOpenStore(new IntPtr(CAPI.CERT_STORE_PROV_MEMORY), 
                                                                           CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, 
                                                                           IntPtr.Zero, 
                                                                           CAPI.CERT_STORE_ENUM_ARCHIVED_FLAG | CAPI.CERT_STORE_CREATE_NEW_FLAG, 
                                                                           null);
            if (safeTargetStoreHandle == null || safeTargetStoreHandle.IsInvalid)
                throw new CryptographicException(Marshal.GetLastWin32Error());

            // FindByCert will throw an exception in case of failures.
            FindByCert(safeSourceStoreHandle, 
                       dwFindType,
                       pvFindPara, 
                       validOnly, 
                       pfnCertCallback1,
                       pfnCertCallback2, 
                       pvCallbackData1,
                       pvCallbackData2, 
                       safeTargetStoreHandle);

            pb.Dispose();
            return safeTargetStoreHandle;
        }
Ejemplo n.º 42
0
        private static DateTime SystemTimeToDateTime( ref SYSTEMTIME st )
        {
            System.Runtime.InteropServices.ComTypes.FILETIME ft = new System.Runtime.InteropServices.ComTypes.FILETIME();

            NativeMethods.SystemTimeToFileTime( ref st, out ft );

            DateTime dt = new DateTime( ( ( (long) ft.dwHighDateTime ) << 32 ) | (uint) ft.dwLowDateTime );

            return dt;
        }
Ejemplo n.º 43
0
		static long ConvertToLong(FILETIME filetime) {

			// File time effectively has a long split into 2 ints.
			// So to recreate the long we stick them back together (moving the 'high' bit to the bits in the top end of the long)
			return ConvertToLong(filetime.dwHighDateTime, filetime.dwLowDateTime);
		}
 public static bool FsSetTime(string remoteName, FILETIME creationTime, FILETIME lastAccessTime, FILETIME lastWriteTime)
 {
     var result = false;
     try
     {
         result = Plugin.SetFileTime(
             remoteName,
             DateTimeUtil.FromFileTime(creationTime),
             DateTimeUtil.FromFileTime(lastAccessTime),
             DateTimeUtil.FromFileTime(lastWriteTime)
         );
     }
     catch (Exception ex)
     {
         UnhandledError(ex);
     }
     return result;
 }
 public extern virtual HRESULT SetDate(string pszPropertyName, uint dwFlags, FILETIME ftDateTime);
Ejemplo n.º 46
0
		public int GetLastSyncTime(out System.Runtime.InteropServices.ComTypes.FILETIME pftLastSync)
		{
			pftLastSync = new System.Runtime.InteropServices.ComTypes.FILETIME();
			pftLastSync.dwHighDateTime = 0;
			pftLastSync.dwLowDateTime = 0;
			return 0;
		}
Ejemplo n.º 47
0
        //------------------------------------------------------------------------------
        public short Get()
        {
            short cpuCopy = m_nUsoCPU;
              if (Interlocked.Increment(ref m_nContador) == 1)
              {
            if (!EnoughTimePassed)
            {
              Interlocked.Decrement(ref m_nContador);
              return cpuCopy;
            }

            ComTypes.FILETIME sysIdle, sysKernel, sysUser;
            TimeSpan procTiempo;

            Process process = Process.GetCurrentProcess();
            procTiempo = process.TotalProcessorTime;

            if (!GetSystemTimes(out sysIdle, out sysKernel, out sysUser))
            {
              Interlocked.Decrement(ref m_nContador);
              return cpuCopy;
            }

            if (!bPrimeraVez)
            {
              UInt64 sysKernelDiff = SubtractTimes(sysKernel, m_nKernel);
              UInt64 sysUserDiff = SubtractTimes(sysUser, m_nUser);

              UInt64 sysTotal = sysKernelDiff + sysUserDiff;

              Int64 procTotal = procTiempo.Ticks - m_nTime.Ticks;

              if (sysTotal > 0)
              {
            m_nUsoCPU = (short)((100.0 * procTotal) / sysTotal);
              }
            }

            m_nTime = procTiempo;
            m_nKernel = sysKernel;
            m_nUser = sysUser;

            m_nLastTime = DateTime.Now;

            cpuCopy = m_nUsoCPU;
              }
              Interlocked.Decrement(ref m_nContador);

              return cpuCopy;
        }
 public static DateTime? FromFileTime(FILETIME fileTime)
 {
     var longTime = LongUtil.MakeLong(fileTime.dwHighDateTime, fileTime.dwLowDateTime);
     return longTime != 0 ? DateTime.FromFileTime(longTime) : (DateTime?)null;
 }
Ejemplo n.º 49
0
 internal static unsafe int BuildChain(IntPtr hChainEngine, System.Security.Cryptography.SafeCertContextHandle pCertContext, X509Certificate2Collection extraStore, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, TimeSpan timeout, ref SafeCertChainHandle ppChainContext)
 {
     if (pCertContext == null || pCertContext.IsInvalid)
         throw new ArgumentException(SecurityResources.GetResourceString("Cryptography_InvalidContextHandle"), "pCertContext");
     SafeCertStoreHandle hAdditionalStore = SafeCertStoreHandle.InvalidHandle;
     if (extraStore != null && extraStore.Count > 0)
         hAdditionalStore = X509Utils.ExportToMemoryStore(extraStore);
     CAPI.CERT_CHAIN_PARA pChainPara = new CAPI.CERT_CHAIN_PARA();
     pChainPara.cbSize = (uint)Marshal.SizeOf((object)pChainPara);
     SafeLocalAllocHandle localAllocHandle1 = SafeLocalAllocHandle.InvalidHandle;
     if (applicationPolicy != null && applicationPolicy.Count > 0)
     {
         pChainPara.RequestedUsage.dwType = 0U;
         pChainPara.RequestedUsage.Usage.cUsageIdentifier = (uint)applicationPolicy.Count;
         localAllocHandle1 = X509Utils.CopyOidsToUnmanagedMemory(applicationPolicy);
         pChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = localAllocHandle1.DangerousGetHandle();
     }
     SafeLocalAllocHandle localAllocHandle2 = SafeLocalAllocHandle.InvalidHandle;
     if (certificatePolicy != null && certificatePolicy.Count > 0)
     {
         pChainPara.RequestedIssuancePolicy.dwType = 0U;
         pChainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint)certificatePolicy.Count;
         localAllocHandle2 = X509Utils.CopyOidsToUnmanagedMemory(certificatePolicy);
         pChainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = localAllocHandle2.DangerousGetHandle();
     }
     pChainPara.dwUrlRetrievalTimeout = (uint)timeout.Milliseconds;
     System.Runtime.InteropServices.ComTypes.FILETIME pTime = new System.Runtime.InteropServices.ComTypes.FILETIME();
     *(long*)&pTime = verificationTime.ToFileTime();
     uint dwFlags = X509Utils.MapRevocationFlags(revocationMode, revocationFlag);
     if (!CAPI.CAPISafe.CertGetCertificateChain(hChainEngine, pCertContext, ref pTime, hAdditionalStore, ref pChainPara, dwFlags, IntPtr.Zero, out ppChainContext))
         return Marshal.GetHRForLastWin32Error();
     localAllocHandle1.Dispose();
     localAllocHandle2.Dispose();
     return 0;
 }
Ejemplo n.º 50
0
        public bool Update()
        {
            try
            {
                ComTypes.FILETIME sysIdle, sysKernel, sysUser;

                if (!_initialized)
                {
                    _initialized = Init();
                    return _initialized;
                }

                // Check if we can get current system cpu times
                if (!GetSystemTimes(out sysIdle, out sysKernel, out sysUser))
                    return false;

                // Calculate tot system cpu time
                var sysKernelDiff = SubtractTimes(sysKernel, _lastSysKernel);
                var sysUserDiff = SubtractTimes(sysUser, _lastSysUser);
                var sysIdleDiff = SubtractTimes(sysIdle, _lastSysIdle);
                var sysTotal = sysKernelDiff + sysUserDiff;

                if (!validDiff((long)sysKernelDiff) || !validDiff((long)sysUserDiff) || !validDiff((long)sysIdleDiff))
                {
                    Debug.WriteLine("Stats: Negative Tick Difference");
                    Debug.WriteLine("kernel: {0,-20} :: {1,-20} Diff:{2,-20} :: {3} miliseconds", ((UInt64)(sysKernel.dwHighDateTime << 32)) | (UInt64)sysKernel.dwLowDateTime, ((UInt64)(_lastSysKernel.dwHighDateTime << 32)) | (UInt64)_lastSysKernel.dwLowDateTime, sysKernelDiff, TimeSpan.FromTicks((long)sysKernelDiff).TotalMilliseconds);
                    Debug.WriteLine("user  : {0,-20} :: {1,-20} Diff:{2,-20} :: {3} miliseconds", ((UInt64)(sysUser.dwHighDateTime << 32)) | (UInt64)sysUser.dwLowDateTime, ((UInt64)(_lastSysUser.dwHighDateTime << 32)) | (UInt64)_lastSysUser.dwLowDateTime, sysUserDiff, TimeSpan.FromTicks((long)sysUserDiff).TotalMilliseconds);
                    Debug.WriteLine("idle  : {0,-20} :: {1,-20} Diff:{2,-20} :: {3} miliseconds", ((UInt64)(sysIdle.dwHighDateTime << 32)) | (UInt64)sysIdle.dwLowDateTime, ((UInt64)(_lastSysIdle.dwHighDateTime << 32)) | (UInt64)_lastSysIdle.dwLowDateTime, sysIdleDiff, TimeSpan.FromTicks((long)sysIdleDiff).TotalMilliseconds);

                    glitchRecover = true; // mark to recover from glitch
                    _lastSysKernel = sysKernel;
                    _lastSysUser = sysUser;
                    _lastSysIdle = sysIdle;
                    Thread.Sleep(100);// give windows time to recover
                    return Update();
                }

                // Calculate total Cpu usage
                var totalUsage = sysTotal > 0 ? ((sysTotal - sysIdleDiff) * 100d / sysTotal) : TotalCpuUsage;
                TotalCpuUsage = totalUsage < 0 ? TotalCpuUsage : totalUsage;

                var newList = new HashSet<ProcUsage>();
                foreach (var proc in Process.GetProcesses())
                {
                    try
                    {
                        // Skip proc with id 0
                        if (proc.Id == 0) continue;

                        Int64 procTotal;
                        var oldCpuUsage = 0d;
                        var p = GetById(proc.Id);
                        if (p != null)
                        {
                            procTotal = proc.TotalProcessorTime.Ticks - p.LastProcTime.Ticks;
                            oldCpuUsage = p.Usage.Cpu;
                        }
                        else
                            procTotal = 0;

                        var usage = glitchRecover ? oldCpuUsage : ((100.0 * procTotal) / sysTotal); // Calculate process CPU Usage
                        // Add Process to list
                        newList.Add(new ProcUsage
                        {
                            Process = proc,
                            Usage = new Usage
                            {
                                Cpu = usage,
                                Memory = proc.PrivateMemorySize64
                            },
                            LastProcTime = proc.TotalProcessorTime
                        });
                    }
                    catch
                    {
                        continue;
                    }
                    Thread.Sleep(1); // be nice for cpu
                }

                // Update last system times
                _lastSysKernel = sysKernel;
                _lastSysUser = sysUser;
                _lastSysIdle = sysIdle;

                // unmark glitch recover
                if (glitchRecover)
                {
                    glitchRecover = false;
                    Update(); // Update again
                }

                // Update Process list
                _procUsageList = newList;
            }
            catch (Exception ex)
            {
                Logger.Instance.WriteGlobal(ex.ToString());
                return false;
            }
            return true;
        }
Ejemplo n.º 51
0
		public static DateTime FromFileTime(FILETIME filetime) {

			return DateTime.FromFileTime(ConvertToLong(filetime));
		}
Ejemplo n.º 52
0
 private static DateTime DateTimeFromFILETIME(FILETIME ft)
 {
     ulong l = (uint)ft.dwHighDateTime;
     l <<= 32;
     l |= (uint)ft.dwLowDateTime;
     DateTime dt = DateTime.FromFileTimeUtc((long)l);
     return dt;
 }
Ejemplo n.º 53
0
 /// <summary>
 /// Converts the <see cref="FILETIME"/> structure to the <see cref="DateTime"/>.
 /// </summary>
 /// <param name="fileTime">The <see cref="FILETIME"/> structure.</param>
 /// <returns><see cref="DateTime"/> structure converted.</returns>
 public static DateTime FileTimeToDateTime(FILETIME fileTime)
 {
     return DateTime.FromFileTime(Converter.DoubleIntToLong(fileTime.dwHighDateTime, fileTime.dwLowDateTime));
 }
Ejemplo n.º 54
0
        //
        // Builds a certificate chain.
        //

        internal static unsafe int BuildChain (IntPtr hChainEngine,
                                               SafeCertContextHandle pCertContext,
                                               X509Certificate2Collection extraStore, 
                                               OidCollection applicationPolicy,
                                               OidCollection certificatePolicy,
                                               X509RevocationMode revocationMode,
                                               X509RevocationFlag revocationFlag,
                                               DateTime verificationTime,
                                               TimeSpan timeout,
                                               ref SafeCertChainHandle ppChainContext) {
            if (pCertContext == null || pCertContext.IsInvalid)
                throw new ArgumentException(SR.GetString(SR.Cryptography_InvalidContextHandle), "pCertContext");

            SafeCertStoreHandle hCertStore = SafeCertStoreHandle.InvalidHandle;
            if (extraStore != null && extraStore.Count > 0)
                hCertStore = X509Utils.ExportToMemoryStore(extraStore);

            CAPI.CERT_CHAIN_PARA ChainPara = new CAPI.CERT_CHAIN_PARA();

            // Initialize the structure size.
            ChainPara.cbSize = (uint) Marshal.SizeOf(ChainPara);

            SafeLocalAllocHandle applicationPolicyHandle = SafeLocalAllocHandle.InvalidHandle;
            SafeLocalAllocHandle certificatePolicyHandle = SafeLocalAllocHandle.InvalidHandle;
            try {
                // Application policy
                if (applicationPolicy != null && applicationPolicy.Count > 0) {
                    ChainPara.RequestedUsage.dwType = CAPI.USAGE_MATCH_TYPE_AND;
                    ChainPara.RequestedUsage.Usage.cUsageIdentifier = (uint) applicationPolicy.Count;
                    applicationPolicyHandle = X509Utils.CopyOidsToUnmanagedMemory(applicationPolicy);
                    ChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = applicationPolicyHandle.DangerousGetHandle();
                }

                // Certificate policy
                if (certificatePolicy != null && certificatePolicy.Count > 0) {
                    ChainPara.RequestedIssuancePolicy.dwType = CAPI.USAGE_MATCH_TYPE_AND;
                    ChainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint) certificatePolicy.Count;
                    certificatePolicyHandle = X509Utils.CopyOidsToUnmanagedMemory(certificatePolicy);
                    ChainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = certificatePolicyHandle.DangerousGetHandle();
                }

                ChainPara.dwUrlRetrievalTimeout = (uint) Math.Floor(timeout.TotalMilliseconds);

                _FILETIME ft = new _FILETIME();
                *((long*) &ft) = verificationTime.ToFileTime();

                uint flags = X509Utils.MapRevocationFlags(revocationMode, revocationFlag);

                // Build the chain.
                if (!CAPI.CertGetCertificateChain(hChainEngine,
                                                  pCertContext,
                                                  ref ft,
                                                  hCertStore,
                                                  ref ChainPara,
                                                  flags,
                                                  IntPtr.Zero,
                                                  ref ppChainContext))
                    return Marshal.GetHRForLastWin32Error();
            }
            finally {
                applicationPolicyHandle.Dispose();
                certificatePolicyHandle.Dispose();
            }

            return CAPI.S_OK;
        }
Ejemplo n.º 55
0
        private static SYSTEMTIME DateTimeToSystemTime( DateTime dt )
        {
            SYSTEMTIME st;
            System.Runtime.InteropServices.ComTypes.FILETIME ft = new System.Runtime.InteropServices.ComTypes.FILETIME();

            ft.dwHighDateTime = (int) (dt.Ticks >> 32);
            ft.dwLowDateTime  = (int) (dt.Ticks & 0xFFFFFFFFL);

            NativeMethods.FileTimeToSystemTime( ref ft, out st );

            return st;
        }
        public bool Update()
        {
            ComTypes.FILETIME sysIdle, sysKernel, sysUser;

            // Check if we can get current system cpu times
            if (!GetSystemTimes(out sysIdle, out sysKernel, out sysUser))
                return false;

            // Calculate tot system cpu time
            var sysKernelDiff = SubtractTimes(sysKernel, _lastSysKernel);
            var sysUserDiff = SubtractTimes(sysUser, _lastSysUser);
            var sysTotal = sysKernelDiff + sysUserDiff;

            var newList = new HashSet<ProcUsage>();
            foreach (var proc in Process.GetProcesses())
            {
                try
                {
                    // Skip proc with id 0
                    if (proc.Id == 0) continue;

                    Int64 procTotal;
                    var p = GetById(proc.Id);
                    if (p != null)
                        procTotal = proc.TotalProcessorTime.Ticks - p.LastProcTime.Ticks;
                    else
                        procTotal = 0;

                    // Add Process to list
                    newList.Add(new ProcUsage
                    {
                        Process = proc,
                        Usage = new Usage
                        {
                            Cpu = ((100.0 * procTotal) / sysTotal), // Calculate process CPU Usage
                            Memory = proc.PrivateMemorySize64
                        },
                        LastProcTime = proc.TotalProcessorTime
                    });
                }
                catch
                {
                    continue;
                }
                Thread.Sleep(1); // be nice for cpu
            }

            // Update last system times
            _lastSysKernel = sysKernel;
            _lastSysUser = sysUser;

            // Update Process list
            _procUsageList = newList;
            return true;
        }
Ejemplo n.º 57
0
        // Determines how much actual kernel and user time this thread has actually gotten
        bool GetAnimalThreadTime(out Int64 kernel, out Int64 user)
        {
            if (threadHandleValid)
            {
                ComTypes.FILETIME c = new ComTypes.FILETIME();
                ComTypes.FILETIME e = new ComTypes.FILETIME();
                ComTypes.FILETIME kernelFileTime = new ComTypes.FILETIME();
                ComTypes.FILETIME userFileTime = new ComTypes.FILETIME();

                bool success = (GetThreadTimes(threadHandle, ref c, ref e, ref kernelFileTime, ref userFileTime) > 0);
                if (success)
                {
                    kernel = (((Int64) kernelFileTime.dwHighDateTime) << 32) + kernelFileTime.dwLowDateTime;
                    user = (((Int64) userFileTime.dwHighDateTime) << 32) + userFileTime.dwLowDateTime;
                    return true;
                }
                else
                {
                    kernel = 0;
                    user = 0;
                    return false;
                }
            }
            else
            {
                kernel = 0;
                user = 0;
                return false;
            }
        }
Ejemplo n.º 58
0
 public static DateTime FiletimeToDateTime( FILETIME fileTime )
 {
     long hFT2 = ( ( (long) fileTime.dwHighDateTime ) << 32 ) + fileTime.dwLowDateTime;
     return DateTime.FromFileTime( hFT2 );
 }
Ejemplo n.º 59
0
        /// <summary>
        /// Utility to set a date property on an INativeContactProperties.
        /// </summary>
        /// <param name="contact">The INativeContactProperties to set the value on.</param>
        /// <param name="propertyName">The property to set.</param>
        /// <param name="value">The date value to set to the property.</param>
        /// <returns>HRESULT.</returns>
        /// <remarks>
        /// This is a thin wrapper over the COM INativeContactProperties::SetDate to make it more easily consumable
        /// in .Net.  Behavior and returned error codes should be similar to the native version.
        /// </remarks>
        public static HRESULT SetDate(INativeContactProperties contact, string propertyName, DateTime value)
        {
            Verify.IsNotNull(contact, "contact");
            Verify.IsNotNull(propertyName, "propertyName");

            // If the caller hasn't explicitly set the kind then assume it's UTC
            // so it will be written as read to the Contact.  
            if (value.Kind != DateTimeKind.Local)
            {
                value = new DateTime(value.Ticks, DateTimeKind.Utc);
            }

            long longFiletime = value.ToFileTime();

            var ft = new FILETIME
            {
                dwLowDateTime = (Int32)longFiletime,
                dwHighDateTime = (Int32)(longFiletime >> 32)
            };

            return contact.SetDate(propertyName, ContactValue.CGD_DEFAULT, ft);
        }
Ejemplo n.º 60
0
		public void SetData(List<FileDescriptor> fileDescriptors) {
			// Prepare buffer
			var bytes = new List<byte>();
			// Add FILEGROUPDESCRIPTOR header
			bytes.AddRange(StructureBytes(new NativeMethods.FILEGROUPDESCRIPTOR { cItems = (uint)(fileDescriptors.Count()) }));
			// Add n FILEDESCRIPTORs
			foreach (var fileDescriptor in fileDescriptors) {
				// Set required fields
				var FILEDESCRIPTOR = new NativeMethods.FILEDESCRIPTOR {
					cFileName = fileDescriptor.Name,
				};
				// Set optional timestamp
				if (fileDescriptor.ChangeTimeUtc.HasValue) {
					FILEDESCRIPTOR.dwFlags |= NativeMethods.FD_CREATETIME | NativeMethods.FD_WRITESTIME;
					var changeTime = fileDescriptor.ChangeTimeUtc.Value.ToLocalTime().ToFileTime();
					var changeTimeFileTime = new FILETIME {
						dwLowDateTime =
							(int)(changeTime & 0xffffffff),
						dwHighDateTime =
							(int)(changeTime >> 32),
					};
					FILEDESCRIPTOR.ftLastWriteTime = changeTimeFileTime;
					FILEDESCRIPTOR.ftCreationTime = changeTimeFileTime;
				}
				// Set optional length
				if (fileDescriptor.Length.HasValue) {
					FILEDESCRIPTOR.dwFlags |= NativeMethods.FD_FILESIZE;
					FILEDESCRIPTOR.nFileSizeLow = (uint)(fileDescriptor.Length & 0xffffffff);
					FILEDESCRIPTOR.nFileSizeHigh = (uint)(fileDescriptor.Length >> 32);
				}
				// Add structure to buffer
				bytes.AddRange(StructureBytes(FILEDESCRIPTOR));
			}

			// Set CFSTR_FILEDESCRIPTORW
			switch (Source) {
				case DragAndDropSource.ListView:
					SetData(FILESOURCE, Encoding.ASCII.GetBytes("ListView\0"));
					break;
				case DragAndDropSource.ListViewSearch:
					SetData(FILESOURCE, Encoding.ASCII.GetBytes("ListViewSearch\0"));
					break;
				case DragAndDropSource.TreeView:
					SetData(FILESOURCE, Encoding.ASCII.GetBytes("TreeView\0"));
					break;
				case DragAndDropSource.SpriteEditor:
					SetData(FILESOURCE, Encoding.ASCII.GetBytes("SpriteEditor\0"));
					break;
				case DragAndDropSource.ResourceExtractor:
					SetData(FILESOURCE, Encoding.ASCII.GetBytes("ResourceExtractor\0"));
					break;
				case DragAndDropSource.Other:
					SetData(FILESOURCE, Encoding.ASCII.GetBytes("Other\0"));
					break;
			}
			
			SetData(FILEDESCRIPTORW, bytes);
			// Set n CFSTR_FILECONTENTS
			var index = 0;
			foreach (var fileDescriptor in fileDescriptors) {
				SetData(FILECONTENTS, index, fileDescriptor);
				index++;
			}

		}