public void ToUnixTimeInMilliseconds_DateTimeOffset_ShouldMatch()
        {
            var offset = new DateTimeOffset(2016, 1, 8, 4, 11, 28, TimeSpan.FromHours(7));
            var expected = offset.ToUnixTimeMilliseconds();
            var actual = offset.ToUnixTimeInMilliseconds();

            Assert.AreEqual(expected, actual);
        }
示例#2
0
 public virtual AllureLifecycle StartStep(string parentUuid, string uuid, StepResult stepResult, DateTimeOffset?startTime = null)
 {
     stepResult.stage = Stage.running;
     stepResult.start = startTime?.ToUnixTimeMilliseconds() ?? DateTimeOffset.Now.ToUnixTimeMilliseconds();
     storage.StartStep(uuid);
     storage.AddStep(parentUuid, uuid, stepResult);
     return(this);
 }
示例#3
0
        public virtual AllureLifecycle StopStep(string uuid, DateTimeOffset?stopTime = null)
        {
            var step = storage.Remove <StepResult>(uuid);

            step.stage = Stage.finished;
            step.stop  = stopTime?.ToUnixTimeMilliseconds() ?? DateTimeOffset.Now.ToUnixTimeMilliseconds();
            storage.StopStep();
            return(this);
        }
示例#4
0
文件: TokenDAO.cs 项目: devlaf/carver
        public static async Task <string> Create(IDbConnection dbConnection, string description, DateTimeOffset?expiration)
        {
            var sql = "INSERT INTO tokens (id, description, created_at, expires_at) " +
                      "VALUES (@ID, @Description, @CreatedAt, @ExpiresAt) RETURNING id;";

            var values = new {
                ID          = Guid.NewGuid(),
                Description = description,
                CreatedAt   = DateTimeOffset.Now.ToUnixTimeMilliseconds(),
                ExpiresAt   = expiration?.ToUnixTimeMilliseconds()
            };

            return(await Task.Factory.StartNew <string>(() => dbConnection.QueryFirst <string>(sql, values)));
        }
示例#5
0
        /// <summary>
        /// Get the current unified time
        /// </summary>
        /// <returns></returns>
        private long GetCurrentTime()
        {
            var endPoints = _redisClient.GetEndPoints();

            foreach (var endPoint in endPoints)
            {
                var server = _redisClient.GetServer(_redisClient.GetEndPoints()[0]);
                if (server.IsConnected)
                {
                    var            redisTime = server.Time();
                    DateTimeOffset utcTime   = redisTime;
                    return(utcTime.ToUnixTimeMilliseconds());
                }
            }

            return(0);
        }
示例#6
0
        private async Task WriteFileHeaderAsync()
        {
            var context = _pool.Get();

            try
            {
                context.Writer.Write((uint)ServerReplayVersion.Initial);
                context.Writer.Write(_startTime.ToUnixTimeMilliseconds());
                context.Writer.Write(DotnetUtils.Version);

                await WriteAsync(context.Stream !);
            }
            finally
            {
                _pool.Return(context);
            }
        }
示例#7
0
        public List <EventData> Generate(DateTimeOffset startDate, int sampleCount)
        {
            if (sampleCount <= 0)
            {
                sampleCount = 1;
            }
            var data = new List <EventData>();
            //long runTime = startDate.Subtract(Constants.UnixEpoch).Ticks / 10000;
            long runTime = startDate.ToUnixTimeMilliseconds();

            for (int i = 0; i < sampleCount; i++)
            {
                data.AddRange(Generate(runTime));
                runTime = data.Max(r => r.Timestamp) + 100;
            }
            return(data);
        }
示例#8
0
        protected virtual string HandleValue(object value)
        {
            if (value is Symbol)
            {
                return(value.ToString());
            }
            else if (value is Parameter)
            {
                return(value.ToString());
            }

            if (value == null)
            {
                return("null");
            }
            else
            {
                if (value.GetType().IsDateTime())
                {
                    DateTimeOffset d = value is DateTimeOffset ? (DateTimeOffset)value : (DateTime)value;
                    return(d.ToUnixTimeMilliseconds().ToString());
                }
                else if (value.GetType().IsTimeSpan())
                {
                    return(((TimeSpan)value).TotalMilliseconds.ToString());
                }
                else if (Type.GetTypeCode(value.GetType()) == TypeCode.String)
                {
                    return($"'{value}'");
                }
                else if (value.GetType().IsEnum)
                {
                    return($"{(int)value}");
                }
                else if (value.GetType().IsPrimitive())
                {
                    NumberFormatInfo nfi = new NumberFormatInfo();
                    nfi.NumberDecimalSeparator = ".";
                    return(string.Format(nfi, "{0}", value));
                }
                else
                {
                    throw new ArgumentException($"Unsupported type: '{value.GetType().FullName}'", nameof(value));
                }
            }
        }
示例#9
0
		/// <summary>
		/// Schedules an alarm.
		/// </summary>
		/// <param name="alarm">The alarm to be scheduled.</param>
		public void ScheduleAlarm (Alarm alarm)
		{
			var intent = new Intent (context, typeof (AlarmIntentService));
			// intent.PutExtra (AlarmIntentService.ALARM_KEY, alarm);
			// TODO - workaround https://github.com/googlesamples/android-DirectBoot/issues/4
			intent.PutExtra ("id", alarm.Id);
			intent.PutExtra ("year", alarm.Year);
			intent.PutExtra ("month", alarm.Month);
			intent.PutExtra ("day", alarm.Day);
			intent.PutExtra ("hour", alarm.Hour);
			intent.PutExtra ("minute", alarm.Minute);
			var pendingIntent = PendingIntent.GetService (context, alarm.Id, intent, PendingIntentFlags.UpdateCurrent);
			var triggerOffset = new DateTimeOffset (alarm.GetTriggerTime ());
			var alarmClockInfo = new AlarmManager.AlarmClockInfo (triggerOffset.ToUnixTimeMilliseconds (), pendingIntent);
			alarmManager.SetAlarmClock (alarmClockInfo, pendingIntent);
			Log.Info (TAG, $"Alarm scheduled at {alarm.Hour}:{alarm.Minute} {alarm.Year}-{alarm.Month}-{alarm.Day}");
		}
示例#10
0
        public Models.Response CreateGroup(Models.GroupRequest value, long organization)
        {
            Models.Response response = new Models.Response();

            try
            {
                //SQL Statement
                var sqlString = "INSERT INTO groups (id, name, description, organization) " +
                                "VALUES (@id, @name, @description, @organization)";

                //Create UNIX Timestamp
                var utcDateTime  = DateTime.UtcNow;
                var dto          = new DateTimeOffset(utcDateTime);
                var unixDateTime = dto.ToUnixTimeMilliseconds();

                using (var connection = new NpgsqlConnection(connectionString))
                {
                    connection.Open();

                    using (var command = new NpgsqlCommand(sqlString, connection))
                    {
                        command.Parameters.AddWithValue("@id", NpgsqlTypes.NpgsqlDbType.Bigint, unixDateTime);
                        command.Parameters.AddWithValue("@name", NpgsqlTypes.NpgsqlDbType.Varchar, value.Name);
                        command.Parameters.AddWithValue("@description", NpgsqlTypes.NpgsqlDbType.Varchar, value.Description);
                        command.Parameters.AddWithValue("@organization", NpgsqlTypes.NpgsqlDbType.Bigint, organization);
                        command.Prepare();
                        command.ExecuteNonQuery();

                        //Log Success
                        response.Status  = "success";
                        response.Message = "group created";
                        response.Id      = unixDateTime;
                        return(response);
                    }
                }
            }
            catch (Exception ex)
            {
                //Log Exception
                //_logger.LogError(ex, "group creation failed");
                response.Status  = "error";
                response.Message = "group creation failed";
                response.Id      = 0;
                return(response);
            }
        }
示例#11
0
        static string GenerateClientSecretJWT(DateTimeOffset requestTime, string keyId, string teamId, string p8FileContents)
        {
            var headers = new Dictionary <string, object>
            {
                { "alg", "ES256" },
                { "kid", keyId }
            };

            var payload = new Dictionary <string, object>
            {
                { "iss", teamId },
                { "iat", requestTime.ToUnixTimeMilliseconds() }
            };

            var secretKey = CleanP8Key(p8FileContents);

            // Get our headers/payloads into a json string
            var headerStr  = "{" + string.Join(",", headers.Select(kvp => $"\"{kvp.Key}\":\"{kvp.Value.ToString()}\"")) + "}";
            var payloadStr = "{";

            foreach (var kvp in payload)
            {
                if (kvp.Value is int || kvp.Value is long || kvp.Value is double)
                {
                    payloadStr += $"\"{kvp.Key}\":{kvp.Value.ToString()},";
                }
                else
                {
                    payloadStr += $"\"{kvp.Key}\":\"{kvp.Value.ToString()}\",";
                }
            }
            payloadStr = payloadStr.TrimEnd(',') + "}";


            // Load the key text
            var key = CngKey.Import(Convert.FromBase64String(secretKey), CngKeyBlobFormat.Pkcs8PrivateBlob);

            using var dsa = new ECDsaCng(key);
            var unsignedJwt = Base64UrlEncode(Encoding.UTF8.GetBytes(headerStr))
                              + "." + Base64UrlEncode(Encoding.UTF8.GetBytes(payloadStr));

            var signature = dsa.SignData(Encoding.UTF8.GetBytes(unsignedJwt), HashAlgorithmName.SHA256);

            return(unsignedJwt + "." + Base64UrlEncode(signature));
        }
        public void GetChartData()
        {
            string connstr = WebConfigurationManager.ConnectionStrings["SPCAConnectionString"].ConnectionString;

            SqlConnection conn = new SqlConnection(connstr);

            conn.Open();

            string sql = "SELECT Head, Nose, Haunches, Shoulder, Time_Stamp FROM Movement WHERE Dog_ID=" + Get_Dog_ID(DogDropdown.SelectedValue);

            SqlCommand cmd = new SqlCommand(sql, conn);
            DataTable  dt  = new DataTable();

            dt.Load(cmd.ExecuteReader());

            if (dt.Rows.Count == 0)
            {
                headData     = "[[" + DateTimeOffset.Now.ToUnixTimeMilliseconds() + ",0]]";
                noseData     = "[[" + DateTimeOffset.Now.ToUnixTimeMilliseconds() + ",0]]";
                haunchesData = "[[" + DateTimeOffset.Now.ToUnixTimeMilliseconds() + ",0]]";
                shoulderData = "[[" + DateTimeOffset.Now.ToUnixTimeMilliseconds() + ",0]]";
            }
            else
            {
                headData     = "[";
                noseData     = "[";
                haunchesData = "[";
                shoulderData = "[";
                foreach (DataRow dr in dt.Rows)
                {
                    string         sqltime      = dr["Time_Stamp"].ToString();
                    DateTimeOffset time         = DateTime.Parse(sqltime);
                    long           milliseconds = time.ToUnixTimeMilliseconds();
                    headData     += "[" + milliseconds + ", " + dr["Head"] + "],";
                    noseData     += "[" + milliseconds + ", " + dr["Nose"] + "],";
                    haunchesData += "[" + milliseconds + ", " + dr["Haunches"] + "],";
                    shoulderData += "[" + milliseconds + ", " + dr["Shoulder"] + "],";
                }
                headData     = headData.Remove(headData.Length - 1) + "]";
                noseData     = noseData.Remove(noseData.Length - 1) + "]";
                haunchesData = haunchesData.Remove(haunchesData.Length - 1) + "]";
                shoulderData = shoulderData.Remove(shoulderData.Length - 1) + "]";
            }
            conn.Close();
        }
        /// <summary>
        /// Get issues in a project from the server.
        /// </summary>
        /// <remarks>Uses the REST API <a href="https://www.jetbrains.com/help/youtrack/standalone/Get-Issues-in-a-Project.html">Get Issues in a Project</a>.</remarks>
        /// <param name="projectId">Id of a project to get issues from.</param>
        /// <param name="filter">Apply a filter to issues in a project.</param>
        /// <param name="skip">The number of issues to skip before getting a list of issues.</param>
        /// <param name="take">Maximum number of issues to be returned. Defaults to the server-side default of the YouTrack server instance..</param>
        /// <param name="updatedAfter">Only issues updated after the specified date will be retrieved.</param>
        /// <param name="wikifyDescription">If set to <value>true</value>, then issue description in the response will be formatted ("wikified"). Defaults to <value>false</value>.</param>
        /// <returns>A <see cref="T:System.Collections.Generic.ICollection`1" /> of <see cref="Issue" /> that match the specified parameters.</returns>
        /// <exception cref="T:System.ArgumentNullException">When the <paramref name="projectId"/> is null or empty.</exception>
        /// <exception cref="T:System.Net.HttpRequestException">When the call to the remote YouTrack server instance failed.</exception>
        public async Task <ICollection <Issue> > GetIssuesInProject(string projectId, string filter = null,
                                                                    int?skip = null, int?take = null, DateTime?updatedAfter = null, bool wikifyDescription = false)
        {
            if (string.IsNullOrEmpty(projectId))
            {
                throw new ArgumentNullException(nameof(projectId));
            }

            var queryString = new List <string>(6);

            if (!string.IsNullOrEmpty(filter))
            {
                queryString.Add($"filter={WebUtility.UrlEncode(filter)}");
            }
            if (skip.HasValue)
            {
                queryString.Add($"after={skip}");
            }
            if (take.HasValue)
            {
                queryString.Add($"max={take}");
            }
            if (updatedAfter.HasValue)
            {
                var offset = new DateTimeOffset(updatedAfter.Value);
                queryString.Add($"updatedAfter={offset.ToUnixTimeMilliseconds()}");
            }

            queryString.Add($"wikifyDescription={wikifyDescription}");

            var query = string.Join("&", queryString);

            var client = await _connection.GetAuthenticatedHttpClient();

            var response = await client.GetAsync($"rest/issue/byproject/{projectId}?{query}");

            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                return(null);
            }

            response.EnsureSuccessStatusCode();

            return(JsonConvert.DeserializeObject <ICollection <Issue> >(await response.Content.ReadAsStringAsync()));
        }
示例#14
0
        private void displaydata_event(object sender, EventArgs e)
        {
            DateTimeOffset now = DateTimeOffset.UtcNow;

            current_time = now.ToUnixTimeMilliseconds();

            if (current_time - start_time > 25)
            {
                current_byte_number = 0;
                start_time          = current_time;
                datas.Clear();
            }

            datas.Enqueue((byte)data);

            label_byte_nr.Text   = Convert.ToString(current_byte_number);
            current_byte_number += 1;
        }
        public static string CreateConditionalOrderCanceledMessage(string orderSide, DateTimeOffset lastActTime)
        {
            var message = @"{
    ""action"":""push"",
    ""ch"":""orders#btcusdt"",
    ""data"":
    {
        ""orderSide"":""" + orderSide + @""",
        ""lastActTime"":" + lastActTime.ToUnixTimeMilliseconds() + @",
        ""clientOrderId"":""abc123"",
        ""orderStatus"":""canceled"",
        ""symbol"":""btcusdt"",
        ""eventType"":""deletion""
    }
}";

            return(message);
        }
        public void SetNotification(DateTime dateTime, string title, string message, string notify_id)
        {
            Intent alarmIntent = new Intent(Android.App.Application.Context, typeof(AlarmReceiver));

            alarmIntent.PutExtra("message", message);
            alarmIntent.PutExtra("title", title);
            alarmIntent.PutExtra("notify_id", notify_id);
            int unique_id = 0;

            int.TryParse(notify_id.ToString(), out unique_id);

            PendingIntent  pendingIntent       = PendingIntent.GetBroadcast(Android.App.Application.Context, unique_id, alarmIntent, PendingIntentFlags.UpdateCurrent);
            AlarmManager   alarmManager        = (AlarmManager)Android.App.Application.Context.GetSystemService(Context.AlarmService);
            DateTimeOffset dateOffsetValue     = DateTimeOffset.Parse(dateTime.ToString());
            var            timefornotification = dateOffsetValue.ToUnixTimeMilliseconds();

            alarmManager.Set(AlarmType.RtcWakeup, timefornotification, pendingIntent);
        }
示例#17
0
 public ZMessage PlaceOrder(string orderId, bool isBid, decimal qty, decimal price, DateTimeOffset timestamp, string clientId)
 {
     if (!isStart)
     {
         return(null);
     }
     socket.Send(new ZMessage(new List <ZFrame>
     {
         new ZFrame(MessageType.PLACEORDER),
         new ZFrame(orderId),
         new ZFrame(isBid.ToString()),
         new ZFrame(qty.ToString()),
         new ZFrame(price.ToString()),
         new ZFrame(timestamp.ToUnixTimeMilliseconds()),
         new ZFrame(clientId),
     }));
     return(OnWaitingResponse());
 }
示例#18
0
 /// <inheritdoc cref="BaseStore.SetBlockPerceivedTime(BlockHash, DateTimeOffset)"/>
 public override void SetBlockPerceivedTime(
     BlockHash blockHash,
     DateTimeOffset perceivedTime
     )
 {
     try
     {
         byte[] key = BlockKey(blockHash);
         _blockPerceptionDb.Put(
             key,
             NetworkOrderBitsConverter.GetBytes(perceivedTime.ToUnixTimeMilliseconds())
             );
     }
     catch (Exception e)
     {
         LogUnexpectedException(nameof(SetBlockPerceivedTime), e);
     }
 }
示例#19
0
        public void testTimeStamp()
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));

            TestContext.Progress.WriteLine(startTime);
            DateTime nowTime = DateTime.Now;

            TestContext.Progress.WriteLine(nowTime);
            long unixTime = (long)Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero);

            TestContext.Progress.WriteLine(unixTime);
            TestContext.Progress.WriteLine("==============");

            DateTimeOffset expiresAtOffset = DateTimeOffset.Now;
            var            totalSeconds    = expiresAtOffset.ToUnixTimeMilliseconds();

            TestContext.Progress.WriteLine(totalSeconds);
        }
示例#20
0
        /// <summary>
        /// DateTime时间格式转换为UTC时间戳格式
        /// </summary>
        /// <param name="time"> DateTime时间格式</param>
        /// <param name="isMilliseconds">是否显示毫秒级时间戳,否->秒级</param>
        /// <returns>Unix时间戳格式</returns>
        public static long ToTimeStamp(this DateTime time, bool isMilliseconds = true)
        {
            //System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            // DateTime startTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local);//等价的建议写法

            DateTimeOffset dto = new DateTimeOffset(time);

            if (isMilliseconds)
            {
                //return (long)(time - startTime).TotalMilliseconds;
                return(dto.ToUnixTimeMilliseconds());
            }
            else
            {
                //return (long)(time - startTime).TotalSeconds;
                return(dto.ToUnixTimeSeconds());
            }
        }
示例#21
0
        public async Task UpdateClickupTask(string taskId, DateTimeOffset?dueDate)
        {
            var clickupTask = await _clickupRepository.GetTaskById(taskId);

            if (clickupTask == null)
            {
                return;
            }

            dueDate = dueDate.UpdateTimeZone(_todoistRepository.TodoistTimeZone);

            if (clickupTask.DueDate == dueDate)
            {
                return;
            }

            await _clickupRepository.UpdateTask(taskId, dueDate?.ToUnixTimeMilliseconds());
        }
示例#22
0
        public string Remind(DateTime dateTime, string title, string message)
        {
            Intent alarmIntent = new Intent(Android.App.Application.Context, typeof(AlarmReceiver));

            alarmIntent.PutExtra("message", message);
            alarmIntent.PutExtra("title", title);

            PendingIntent pendingIntent = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
            AlarmManager  alarmManager  = (AlarmManager)Android.App.Application.Context.GetSystemService(Context.AlarmService);
            //Android.App.Application.Context
            //TODO: For demo set after 5 seconds.
            //var timefornotification = (long)(dateTime - new DateTime(1970, 1, 1, Int16.Parse(dateTime.Hour.ToString()), Int16.Parse(dateTime.Minute.ToString()), Int16.Parse(dateTime.Second.ToString()))).TotalMilliseconds;
            DateTimeOffset dateOffsetValue     = DateTimeOffset.Parse(dateTime.ToString());
            var            timefornotification = dateOffsetValue.ToUnixTimeMilliseconds();

            alarmManager.Set(AlarmType.RtcWakeup, timefornotification, pendingIntent);
            return("f**k");
        }
示例#23
0
        /// <summary>
        /// Get the current unified time
        /// </summary>
        /// <returns></returns>
        private async Task <long> GetCurrentTimeAsync()
        {
            var endPoints = _redisClient.GetEndPoints();

            foreach (var endPoint in endPoints)
            {
                var server = _redisClient.GetServer(endPoint);
                if (server.IsConnected)
                {
                    var redisTime = await server.TimeAsync();

                    DateTimeOffset utcTime = redisTime;
                    return(utcTime.ToUnixTimeMilliseconds());
                }
            }

            return(0);
        }
示例#24
0
        public void SolarLighting_SiteLightingForThreeDays()
        {
            var site = new SiteData
            {
                Location = new ServiceCartographic(39.0, -75.77, 0)
            };
            var solarData = new SolarLightingData <SiteData>
            {
                Path          = site,
                AnalysisStart = new DateTimeOffset(2018, 4, 9,
                                                   0, 0, 0, new TimeSpan(0, 0, 0)),
                AnalysisStop = new DateTimeOffset(2018, 4, 11,
                                                  0, 0, 0, new TimeSpan(0, 0, 0)),
                OutputTimeOffset = -4.0f
            };

            var lighting = LightingServices.GetLightingAtASite(solarData).Result;

            // setup expected dates, then test
            var firstSunrise = new DateTimeOffset(2018, 4, 9,
                                                  6, 35, 24, 756, new TimeSpan(-4, 0, 0));
            var firstAstroPmTwilightStop = new DateTimeOffset(2018, 4, 9,
                                                              21, 08, 04, 142, new TimeSpan(-4, 0, 0));

            Assert.That(lighting.Lighting.Count == 3);
            Assert.AreEqual(firstSunrise.ToUnixTimeMilliseconds(),
                            lighting.Lighting[0].Sunrise.ToUnixTimeMilliseconds());
            Assert.AreEqual(firstAstroPmTwilightStop.ToUnixTimeMilliseconds(),
                            lighting.Lighting[0].AstronomicalTwilightPmStop.ToUnixTimeMilliseconds());
            Assert.IsTrue(lighting.Lighting[0].IsRiseDefined);
            Assert.IsTrue(lighting.Lighting[0].IsSetDefined);

            var secondSunset = new DateTimeOffset(2018, 4, 10,
                                                  19, 35, 29, 938, new TimeSpan(-4, 0, 0));

            Assert.AreEqual(secondSunset.ToUnixTimeMilliseconds(),
                            lighting.Lighting[1].Sunset.ToUnixTimeMilliseconds());

            var thirdNauticalPmTwilightStop = new DateTimeOffset(2018, 4, 11,
                                                                 20, 36, 34, 092, new TimeSpan(-4, 0, 0));

            Assert.AreEqual(thirdNauticalPmTwilightStop.ToUnixTimeMilliseconds(),
                            lighting.Lighting[2].NauticalTwilightPmStop.ToUnixTimeMilliseconds());
        }
示例#25
0
 public bool ApprovRejRequisition([FromBody] Requisition req)
 {
     try
     {
         //add the current date to be the approved date.
         DateTime       dateTime     = DateTime.UtcNow.Date;
         DateTimeOffset dt           = new DateTimeOffset(dateTime, TimeSpan.Zero).ToUniversalTime();
         long           date         = dt.ToUnixTimeMilliseconds();
         int            approvedbyid = (int)HttpContext.Session.GetInt32("Id");
         req.ApprovalDate = date;
         req.ApprovedById = approvedbyid;
         dhservice.ApprovRejRequisition(req);
         return(true);
     }
     catch (Exception m)
     {
         throw new Exception(m.Message);
     }
 }
        static InterfaceToHost.HttpRequestEvent AsPersistentProcessInterfaceHttpRequestEvent(
            HttpContext httpContext,
            string httpRequestId,
            DateTimeOffset time)
        {
            return(new InterfaceToHost.HttpRequestEvent
            {
                posixTimeMilli = time.ToUnixTimeMilliseconds(),

                httpRequestId = httpRequestId,

                requestContext = new InterfaceToHost.HttpRequestContext
                {
                    clientAddress = httpContext.Connection.RemoteIpAddress?.ToString(),
                },

                request = Asp.AsPersistentProcessInterfaceHttpRequest(httpContext.Request),
            });
        }
        private static byte[] DateTimeToBytes(DateTimeOffset timestamp)
        {
            var unixTime      = timestamp.ToUnixTimeMilliseconds();
            var unixTimeBytes = BitConverter.GetBytes(unixTime);

            var result = new byte[NumDateBytes];

            if (BitConverter.IsLittleEndian)
            {
                Array.Copy(unixTimeBytes, 2, result, 0, 4);
                Array.Copy(unixTimeBytes, 0, result, 4, 2);
            }
            else
            {
                Array.Copy(unixTimeBytes, 2, result, 0, 6);
            }

            return(result);
        }
        public static string CreateMarketCandlestickUpdateMessage(DateTimeOffset timestamp)
        {
            var message = @"{
  ""ch"": ""market.ethbtc.kline.1min"",
  ""ts"": " + timestamp.ToUnixTimeMilliseconds() + @",
  ""tick"": {
    ""id"": 1489464480,
    ""amount"": 10.11,
    ""count"": 12,
    ""open"": 7962.62,
    ""close"": 7962.63,
    ""low"": 7962.64,
    ""high"": 7962.65,
    ""vol"": 102.30
  }
}";

            return(message);
        }
示例#29
0
        static void Main(string[] args)
        {
            var t = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();


            //2019-04-22T06:00:58.918Z

            var dateTime = new DateTime(2019, 4, 22, 6, 0, 58, 918, DateTimeKind.Utc);

            DateTimeOffset dof = dateTime;

            var x = dof.ToUnixTimeMilliseconds();



            EfSample();

            Console.ReadKey();
        }
示例#30
0
        private void AlarmMedicamento(Medicamento _medicamento)
        {
            Intent myIntent = new Intent(this, typeof(MedicamentoNotification));

            var dateString = Convert.ToString(_medicamento.fecha + " " + _medicamento.hora); // Fecha y hora seleccionado en string

            DateTimeOffset dateOffsetValue = DateTimeOffset.Parse(dateString);
            var            millisec        = dateOffsetValue.ToUnixTimeMilliseconds();

            _idPending = (int)millisec; // Identificar

            // Inicializar al gerente de alarma
            AlarmManager alarmManager = (AlarmManager)GetSystemService(AlarmService);

            // Pasar el contexto, su codigo de solicitud privado, objeto de intencion y bandera
            var pendingIntent = PendingIntent.GetBroadcast(this, _idPending, myIntent, 0);

            alarmManager.Set(AlarmType.RtcWakeup, millisec, pendingIntent);
        }
示例#31
0
        /// <summary>
        /// Schedules an alarm.
        /// </summary>
        /// <param name="alarm">The alarm to be scheduled.</param>
        public void ScheduleAlarm(Alarm alarm)
        {
            var intent = new Intent(context, typeof(AlarmIntentService));

            // intent.PutExtra (AlarmIntentService.ALARM_KEY, alarm);
            // TODO - workaround https://github.com/googlesamples/android-DirectBoot/issues/4
            intent.PutExtra("id", alarm.Id);
            intent.PutExtra("year", alarm.Year);
            intent.PutExtra("month", alarm.Month);
            intent.PutExtra("day", alarm.Day);
            intent.PutExtra("hour", alarm.Hour);
            intent.PutExtra("minute", alarm.Minute);
            var pendingIntent  = PendingIntent.GetService(context, alarm.Id, intent, PendingIntentFlags.UpdateCurrent);
            var triggerOffset  = new DateTimeOffset(alarm.GetTriggerTime());
            var alarmClockInfo = new AlarmManager.AlarmClockInfo(triggerOffset.ToUnixTimeMilliseconds(), pendingIntent);

            alarmManager.SetAlarmClock(alarmClockInfo, pendingIntent);
            Log.Info(TAG, $"Alarm scheduled at {alarm.Hour}:{alarm.Minute} {alarm.Year}-{alarm.Month}-{alarm.Day}");
        }
示例#32
0
        /// <summary>
        /// Validation iOS
        /// </summary>
        /// <param name="param">subumission parameter</param>
        /// <returns>True when successful.</returns>
        /// <remarks>
        /// https://developer.apple.com/documentation/devicecheck/accessing_and_modifying_per-device_data
        /// </remarks>
        public async Task <bool> Validation(IAppleDeviceVerification deviceVerification, DateTimeOffset requestTime, AuthorizedAppInformation app)
        {
            var payload = new ApplePayload()
            {
                DeviceToken = deviceVerification.DeviceToken,
                Timestamp   = requestTime.ToUnixTimeMilliseconds()
            };

            using (var sha = SHA256.Create())
            {
                payload.TransactionId = Convert.ToBase64String(
                    sha.ComputeHash(Encoding.UTF8.GetBytes(deviceVerification.TransactionIdSeed))
                    );
            }

            Logger.LogInformation($"{nameof(Validation)} DeviceCheckKeyId:{app.DeviceCheckKeyId} DeviceCheckTeamId:{app.DeviceCheckTeamId} DeviceCheckPrivateKey:{app.DeviceCheckPrivateKey}");

            var jwt = GenerateClientSecretJWT(requestTime, app.DeviceCheckKeyId, app.DeviceCheckTeamId, app.DeviceCheckPrivateKey);

            var payloadJson = JsonConvert.SerializeObject(payload);

            Logger.LogInformation($"{nameof(Validation)} payload:{payloadJson} ");
            var request = new HttpRequestMessage(HttpMethod.Post, UrlApple);

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
            request.Content = new StringContent(payloadJson, Encoding.UTF8, "application/json");
            try
            {
                var response = await ClientApple.SendAsync(request);

                if (!response.IsSuccessStatusCode)
                {
                    Logger.LogWarning($"iOS device check failed.\r\n{nameof(HttpRequestMessage)} : {request}\r\n{nameof(HttpResponseMessage)} : {response}");
                }

                return(response.StatusCode == System.Net.HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, $"{nameof(Validation)}");
                throw;
            }
        }
 public static string DelayedActionToString(string action, DateTimeOffset dueTime, bool executed, string guid, string location)
 {
     return string.Format("{0},{1},{2},{3},{4}\n", guid, dueTime.ToUnixTimeMilliseconds(), executed, action, location);
 }
 public static string BeaconEventStateToString(string pid, BeaconEventType type, DateTimeOffset now)
 {
     return string.Format("{0},{1},{2}", pid, (int)type, now.ToUnixTimeMilliseconds());
 }
示例#35
0
 private static DateTimeOffset StripMicroSeconds(DateTimeOffset t)
 {
     // We can't use DateTimeOffsets to compare since the resolution of a ulid is milliseconds, and DateTimeOffset
     // has microseconds and more. So we drop that part by converting to UnixTimeMilliseconds and then back to
     // a DateTimeOffset.
     return DateTimeOffset.FromUnixTimeMilliseconds(t.ToUnixTimeMilliseconds());
 }
示例#36
0
        ///<summary>
        /// HookCallback function
        /// 
        /// Called each time a Hook Event is fired. If the type of event is a KeyPress append the keypress and metadata to a keypress log.
        /// This function calls the next hook in the hook chain.
        ///</summary>
        private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if ((client != null) && (client.Channel.State != ChannelState.FatalFailure)){
                if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
                {
                    // Create a KeyPress object and get keypress metadata.
                    KeyPress ks = new KeyPress();
                    DateTimeOffset x = new DateTimeOffset(DateTime.Now);
                    ks.Key = Marshal.ReadInt32(lParam);
                    ks.Timestamp = x.ToUnixTimeMilliseconds();
                    ks.ActiveProgram = GetActiveWindowName();

                    // Un-Comment these lines to write the KeyStrokes in the JSON human readable format. C# proto
                    // implementation lacks support for the Text encoding, the json encoding is the most human readable format.
                    //StreamWriter o = new StreamWriter(log+".json");
                    //o.WriteLine(ks.ToString());
                    //o.Close();
                    try {
                        client.PutKeyPressAsync(ks);
                    }
                    catch (RpcException e)
                    {
                        //Console.WriteLine("RPC Failed: " + e);
                    }
                }
            }

            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }
 internal static string ActionToString(string uuid, string beaconPid, DateTimeOffset timestamp, int beaconEventType, bool delivered, bool background, string location)
 {
     return string.Format("{0},{1},{2},{3},{4},{5},{6}\n", uuid, beaconPid, timestamp.ToUnixTimeMilliseconds(), beaconEventType, delivered, background, location);
 }