Beispiel #1
0
 public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
 {
     // Unix timestamp is seconds past epoch
     DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
     dtDateTime = dtDateTime.AddSeconds(unixTimeStamp);
     return dtDateTime;
 }
            public static DateTime InstantToDateTime(double instant, DateTime start, TimeUnits units = TimeUnits.SECONDS)
            {
                DateTime instantAsDate = start;

                switch (units)
                {
                   case TimeUnits.YEARS:
                  instantAsDate = start.AddYears((int)instant);
                  break;
                   case TimeUnits.MONTHS:
                  instantAsDate = start.AddMonths((int)instant);
                  break;
                   case TimeUnits.DAYS:
                  instantAsDate = start.AddDays(instant);
                  break;
                   case TimeUnits.HOURS:
                  instantAsDate = start.AddHours(instant);
                  break;
                   case TimeUnits.MINUTES:
                  instantAsDate = start.AddMinutes(instant);
                  break;
                   case TimeUnits.SECONDS:
                  instantAsDate = start.AddSeconds(instant);
                  break;
                }

                return instantAsDate;
            }
        public List <JiveDEAActivityInstance> GetLoginActivity(DateTime?before = null, DateTime?after = null)
        {
            // Jive's DES server seems to off by a few seconds. When making calls using before or after, if either is ahead of the Jive's server, we get a 400 Bad Request Error.
            // For that reason, we push back the these values by 20 seconds. It should be noted that this is problem may get resolved later or not appear on certain clients.
            // Still getting these errors every once in a while, so bumping up to 30 seconds
            //so basically this is the url for getting the general api call  https:// api.jivesoftware.com/analytics/v2/export/activity?count=100&show-all=false&after=2018-05-18T14:00:00.000&before=2018-05-18T14:20:00.000&fields=actorID,actionObjectType,actionObjectId,timestamp&filter
            before = before?.AddSeconds(-30);
            after  = after?.AddSeconds(-30);

            List <JiveDEAActivityInstance> activityList = new List <JiveDEAActivityInstance>();

            string url = _desUrl + "/activity/lasthour?filter=action(Login)";

            // jive returns a paginated list, so we have to loop through all of the pages.
            while (true)
            {
                string json;
                try
                {
                    json = GetAbsolute(url, getAuthorization(true));
                }
                catch (HttpException e)
                {
                    switch (e.GetHttpCode())
                    {
                    case 400:
                        throw new HttpException(e.WebEventCode, "An input field is missing or malformed", e);

                    case 403:
                        throw new HttpException(e.WebEventCode, "You are not allowed to access this", e);

                    case 401:     // If the token happens to have expired, try once more before giving up.
                        json = retry(url);
                        break;

                    default:
                        throw;
                    }
                }
                JObject results = JObject.Parse(json);


                activityList.AddRange(results["list"].ToObject <List <JiveDEAActivityInstance> >());

                if (results["paging"] == null || results["paging"]["next"] == null)
                {
                    break;
                }
                else
                {
                    url = results["paging"]["next"].ToString();
                }
            }
            return(activityList);
        }
Beispiel #4
0
        /// <summary>Сортирует и вычисляет позиции</summary>
        /// <param name="queue">Извлечённая из БД очередь для пересчёта</param>
        /// <param name="sortBy">Применяемая сортировка</param>
        /// <param name="forceOutput">Принудительная установка времени ожидания первому клиенту</param>
        /// <returns></returns>
        private static IEnumerable <Model.IQueue> SortAndCalculatePositions(
            IEnumerable <Model.IQueue> queue, SortPositionsEnum sortBy, DateTime?forceOutput = null)
        {
            DateTime now = DateTime.Now;

            now = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, int.Parse(now.Millisecond.ToString(new string('0', Repository.EntityDatetimePrecision))));

            var result = new List <Model.IQueue>();

            if (sortBy == SortPositionsEnum.Input)
            {
                result = queue.OrderBy(t => t.Input).Select((t, index) => new Model.Queue()
                {
                    Position = index + 1,
                    Output   = forceOutput? // расчётное время первой позиции равно текущему
                               .AddSeconds(OutputForecastParam * (index))
                               ?? now.AddSeconds(OutputForecastParam * (index)),
                    Input         = t.Input,
                    ParkingCard   = t.ParkingCard,
                    Rotation      = t.Rotation,
                    RotationStart = t.RotationStart
                }).Cast <Model.IQueue>().ToList();
            }

            if (sortBy == SortPositionsEnum.Position)
            {
                result = queue.OrderBy(t => t.Position).Select((t, index) => new Model.Queue()
                {
                    Position = t.Position,
                    Output   = forceOutput? // расчётное время первой позиции равно текущему
                               .AddSeconds(OutputForecastParam * (index))
                               ?? now.AddSeconds(OutputForecastParam * (index)),
                    Input       = t.Input,
                    ParkingCard = t.ParkingCard,
                    Rotation    = t.Rotation
                }).Cast <Model.IQueue>().ToList();
            }

            return(result);
        }
Beispiel #5
0
 /// <summary> 
 /// 在C#中指定修订号为*的时候,修订号则是一个时间戳,我们可以从其得到编译日期
 /// 生成和修订版本号必须是自动生成的
 /// AssemblyInfo里的写法应该为1.0之后为.*
 /// [assembly: AssemblyVersion("1.0.*")]
 /// </summary>
 /// <returns></returns>
 public DateTime GetBuildDateTime()
 {
     /*
      * version = 1.0.3420.56234
      * 这里主版本号是1,次版本号是0,而生成和修订版本号是自动生成的。
      * 使用*时,生成号是从2000年1月1日开始的天数,而修订号是从凌晨开始的秒数除以2。
      */
     string version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
     int days = 0;
     int seconds = 0;
     string[] v = version.Split('.');
     if (v.Length == 4)
     {
         days = Convert.ToInt32(v[2]);
         seconds = Convert.ToInt32(v[3]);
     }
     DateTime dt = new DateTime(2000, 1, 1);
     dt = dt.AddDays(days);
     dt = dt.AddSeconds(seconds * 2);
     return dt;
 }
            public static DateTime GetLinkerTimestamp(Assembly assembly = null)
            {
                var asm = assembly ?? Assembly.GetCallingAssembly();
                var filePath = asm.Location;
                const int peHeaderOffset = 60;
                const int linkerTimestampOffset = 8;
                var b = new byte[2048];
                Stream s = null;

                try
                {
                    s = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    s.Read(b, 0, 2048);
                }
                finally
                {
                    s?.Close();
                }

                var i = BitConverter.ToInt32(b, peHeaderOffset);
                var secondsSince1970 = BitConverter.ToInt32(b, i + linkerTimestampOffset);
                var dt = new DateTime(1970, 1, 1, 0, 0, 0);
                return dt.AddSeconds(secondsSince1970);
            }
        internal AccessTokenResponse GetSuitableToUpdateLoginInfo()
        {
            using (tokenChangeLock.ReaderLock())
            {
                if (loginInfo?.RefreshToken == null)
                {
                    return(null);
                }

                // no need refresh
                if (accessTokenValidTo >= DateTime.UtcNow.AddSeconds(domain0AuthenticationContext.ReserveTimeToUpdate))
                {
                    return(null);
                }

                // can't refresh
                if (refreshTokenValidTo?.AddSeconds(domain0AuthenticationContext.ReserveTimeToUpdate) <= DateTime.UtcNow)
                {
                    return(null);
                }

                return(loginInfo);
            }
        }
Beispiel #8
0
 public static object column(this sqlite3_stmt stmt, int index, Type t)
 {
     if (typeof(String) == t)
     {
         return(stmt.column_text(index));
     }
     else if (
         (typeof(Int32) == t) ||
         (typeof(Boolean) == t) ||
         (typeof(Byte) == t) ||
         (typeof(UInt16) == t) ||
         (typeof(Int16) == t) ||
         (typeof(sbyte) == t)
         )
     {
         return(Convert.ChangeType(stmt.column_int(index), t, null));
     }
     else if (
         (typeof(double) == t) ||
         (typeof(float) == t)
         )
     {
         return(Convert.ChangeType(stmt.column_double(index), t, null));
     }
     else if (typeof(DateTime) == t)
     {
         DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
         return(origin.AddSeconds(stmt.column_int64(index)));
     }
     else if (
         (typeof(Int64) == t) ||
         (typeof(UInt32) == t)
         )
     {
         return(Convert.ChangeType(stmt.column_int64(index), t, null));
     }
     else if (typeof(System.Nullable <long>) == t)
     {
         if (stmt.column_type(index) == raw.SQLITE_NULL)
         {
             return(null);
         }
         else
         {
             long?x = stmt.column_int64(index);
             return(x);
         }
     }
     else if (typeof(System.Nullable <double>) == t)
     {
         if (stmt.column_type(index) == raw.SQLITE_NULL)
         {
             return(null);
         }
         else
         {
             double?x = stmt.column_double(index);
             return(x);
         }
     }
     else if (typeof(System.Nullable <int>) == t)
     {
         if (stmt.column_type(index) == raw.SQLITE_NULL)
         {
             return(null);
         }
         else
         {
             int?x = stmt.column_int(index);
             return(x);
         }
     }
     else if (typeof(decimal) == t)
     {
         return((decimal)Convert.ChangeType(stmt.column_double(index), t, null));
     }
     else if (typeof(byte[]) == t)
     {
         return(stmt.column_blob(index));
     }
     else
     {
         throw new NotSupportedException("Invalid type conversion" + t);
     }
 }
        public override void OnDoubleClick(Mobile from)
        {
            if (m_sower == null || m_sower.Deleted)
            {
                m_sower = from;
            }
            if (from != m_sower)
            {
                from.SendMessage("You do not own this plant !!!"); return;
            }

            if (from.Mounted && !CropHelper.CanWorkMounted)
            {
                from.SendMessage("You cannot harvest a crop while mounted."); return;
            }
            if (DateTime.UtcNow > lastpicked.AddSeconds(3))
            {
                lastpicked = DateTime.UtcNow;
                int cookValue = (int)from.Skills[SkillName.Cooking].Value / 20;
                if (cookValue == 0)
                {
                    from.SendMessage("You have no idea how to harvest this crop."); return;
                }
                if (from.InRange(this.GetWorldLocation(), 1))
                {
                    if (m_yield < 1)
                    {
                        from.SendMessage("There is nothing here to harvest.");
                    }
                    else
                    {
                        from.Direction = from.GetDirectionTo(this);
                        from.Animate(from.Mounted ? 29:32, 5, 1, true, false, 0);
                        m_lastvisit = DateTime.UtcNow;
                        if (cookValue > m_yield)
                        {
                            cookValue = m_yield + 1;
                        }
                        int pick = Utility.RandomMinMax(cookValue - 4, cookValue);
                        if (pick < 0)
                        {
                            pick = 0;
                        }
                        if (pick == 0)
                        {
                            from.SendMessage("You do not manage to harvest any crops."); return;
                        }
                        m_yield -= pick;
                        from.SendMessage("You harvest {0} crop{1}!", pick, (pick == 1 ? "" : "s"));
                        if (m_yield < 1)
                        {
                            ((Item)this).ItemID = pickedGraphic;
                        }
                        Pistacio crop = new Pistacio(pick);
                        from.AddToBackpack(crop);
                        if (!regrowTimer.Running)
                        {
                            regrowTimer.Start();
                        }
                    }
                }
                else
                {
                    from.SendMessage("You are too far away to harvest anything.");
                }
            }
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            // Because I don't like magic numbers
            const int SECONDS_PER_DAY = 86400; // 60 seconds * 60 minutes * 24 hours

            // Create the database connection
            var db = new LocationsEventsContext();

            // Add the locations if they don't exist
            int LocationCount = db.Locations.Count();

            Console.WriteLine("Locations: " + LocationCount);
            if (LocationCount < 3)
            {
                db.AddLocation(new Location {
                    Name = "Family Room"
                });
                db.AddLocation(new Location {
                    Name = "Front Door"
                });
                db.AddLocation(new Location {
                    Name = "Rear Door"
                });

                // Write out the number of locations after the update
                LocationCount = db.Locations.Count();
                Console.WriteLine("Locations After Update: {0}", LocationCount);
            }
            ;

            // Get the locations, the var will be converted to a list
            var Locations = (from Location in db.Locations select Location).ToList();

            // Show the location ids exist
            foreach (var Location in Locations)
            {
                Console.WriteLine("Location ID = {0}, Name = {1}", Location.LocationId, Location.Name);
            }

            // Set the staring date 6 months ago
            DateTime Today = DateTime.Now.Date;

            Console.WriteLine("Date Today: {0:R}", Today);
            DateTime ProcessDate = Today.AddMonths(-6);

            Console.WriteLine("Date Start: {0:R}", ProcessDate);
            DateTime LocationEventDateTime;

            // Create the variables needed for the events
            Random RandomNum = new Random();
            int    NumberOfEvents;
            int    lcv; // Loop control variable
            int    Index;

            do
            {
                NumberOfEvents = RandomNum.Next(0, 6);
                Console.WriteLine("Processing {0} Events for    Date: {1:R}", NumberOfEvents, ProcessDate);

                // By setting lcv = 1, the loop will be skipped for zero events
                for (lcv = 1; lcv <= NumberOfEvents; lcv++)
                {
                    //Console.WriteLine ("\tProcessing Event {0} for Date: {1:d}", lcv, ProcessDate);

                    Index = RandomNum.Next(LocationCount);
                    LocationEventDateTime = ProcessDate.AddSeconds(RandomNum.Next(SECONDS_PER_DAY));
                    Console.WriteLine("\tProcessing Event {0} Date: {1:R} Location {2} - {3}", lcv, LocationEventDateTime, Locations[Index].LocationId, Locations[Index].Name);

                    Event NewEvent = new Event {
                        TimeStamp  = LocationEventDateTime,
                        LocationId = Locations[Index].LocationId
                    };

                    db.AddEvent(NewEvent);
                }

                ProcessDate = ProcessDate.AddDays(1);
            } while (ProcessDate <= Today);
        }
Beispiel #11
0
        /// <summary>
        /// 后台读取线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void bWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;

            //处理过程
            while (!bw.CancellationPending)
            {
                //判断通道是否可用
                if (channelStateReady)
                {
                    //从通道中读取数据对象,若返回值为null 则表示无数据或读取出错(读取出错处理在 read方法进行处理)
                    CMPPMsgBody_Base data = read();
                    if (data != null)
                    {
                        channelLastUpdate = DateTime.Now;
                        //对读取到的数据进行处理
                        switch (data.MyHead.Command_Id)
                        {
                            #region 命令响应
                        case Command_Id.CMPP_SUBMIT_RESP:
                        case Command_Id.CMPP_ACTIVE_TEST_RESP:
                            if (CmppCmdQueue.ContainsKey(data.MyHead.Sequence_Id))
                            {
                                CmppCmdQueue[data.MyHead.Sequence_Id] = data;
                            }
                            break;

                            #endregion
                            #region 状态回报 上行
                        case Command_Id.CMPP_DELIVER:
                            ThreadPool.QueueUserWorkItem(ThreadPoolExcuteFuctione, data);
                            //响应服务器
                            CMPP_DELIVER      deliver     = data as CMPP_DELIVER;
                            CMPP_DELIVER_RESP deliverResp =
                                new CMPP_DELIVER_RESP(deliver.MyHead.Sequence_Id, deliver.Msg_Id, (uint)DeliverResult.正确);
                            Submit(deliverResp);
                            break;

                            #endregion
                            #region 拆除连接
                        case Command_Id.CMPP_TERMINATE:
                            Submit(new CMPP_TERMINATE_RESP(data.MyHead.Sequence_Id));
                            CloseSoket();
                            break;

                            #endregion
                            #region 连接检测
                        case Command_Id.CMPP_ACTIVE_TEST:
                            Submit(new CMPP_ACTIVE_TEST_RESP(data.MyHead.Sequence_Id));
                            break;

                            #endregion
                        default:    //未知的命令丢弃
                            break;
                        }
                    }
                }
                //判断通道空闲时间间隔,进行超时处理
                if (channelLastUpdate.AddSeconds(ActiveTestInterval) < DateTime.Now)
                {
                    var err = Submit(new CMPP_ACTIVE_TEST());//
                    if (err != LocalErrCode.成功)
                    {
                        channelLastUpdate = channelLastUpdate.AddSeconds(ActiveTestInterval);//n秒后重试 防止过多发送
                        WriteLog("长连接链路检测发送失败:" + err.ToString());
                    }
                }
                Thread.Sleep(10);//每个周期休眠10毫秒
            }
        }
Beispiel #12
0
        public static DateTime FromUnixTime(ulong unixTime)
        {
            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            return(epoch.AddSeconds(unixTime));
        }
 private bool IsTimedOut(DateTime startTime)
 {
     return(!configuration.Timeout.Equals(0) && startTime.AddSeconds(configuration.Timeout) < DateTime.UtcNow);
 }
Beispiel #14
0
        public bool IsNeedKill()
        {
            DateTime endLiveTime = lastUserMessage.AddSeconds(ChatSessionSettings.ChatSessionLiveTime);

            return(endLiveTime <= DateTime.UtcNow);
        }
Beispiel #15
0
        private static async Task <CityData> FormatResult(CityData _CityData, DataFormat _DataFormat)
        {
            var loader      = new ResourceLoader();
            var dateTime    = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var _Visibility = Convert.ToDouble(_CityData.Current.visibility) / 1000;

            _CityData.Current.Date = dateTime.AddSeconds(_CityData.Current.dt).ToLocalTime().ToString("ddd, dd MMM");

            if (_DataFormat.TimeFormat == "24h")
            {
                _CityData.Current.SunriseSunset = dateTime.AddSeconds(_CityData.Current.sys.sunrise).ToLocalTime().ToString("H:mm") + "/" + dateTime.AddSeconds(_CityData.Current.sys.sunset).ToLocalTime().ToString("H:mm");
            }
            else
            {
                _CityData.Current.SunriseSunset = dateTime.AddSeconds(_CityData.Current.sys.sunrise).ToLocalTime().ToString("h:mmtt") + "/" + dateTime.AddSeconds(_CityData.Current.sys.sunset).ToLocalTime().ToString("h:mmtt");
            }

            if (_DataFormat.UnitsFormat == "metric")
            {
                _CityData.Current.wind.speed = _CityData.Current.wind.speed + loader.GetString("MeterSec");
                _CityData.Current.visibility = _Visibility + loader.GetString("Kilometer");
            }
            else
            {
                _CityData.Current.wind.speed = _CityData.Current.wind.speed + loader.GetString("MileHour");
                _CityData.Current.visibility = Math.Round(_Visibility * 0.62, 0) + loader.GetString("Mile");
            }

            StorageFolder _assets = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");

            StorageFolder _icons = await _assets.GetFolderAsync("Icons");

            _CityData.Current.main.temp              = Math.Round(_CityData.Current.main.temp, 0);
            _CityData.Current.main.pressure          = _CityData.Current.main.pressure + loader.GetString("PressureUnit");
            _CityData.Current.weather[0].description = char.ToUpper(_CityData.Current.weather[0].description[0]) + _CityData.Current.weather[0].description.Substring(1);
            if (await _icons.TryGetItemAsync(_CityData.Current.weather[0].icon + ".png") != null)
            {
                _CityData.Current.Image = "ms-appx:///Assets/Icons/" + _CityData.Current.weather[0].icon + ".png";
            }
            else
            {
                _CityData.Current.Image = "ms-appx:///Assets/Icons/02n.png";
            }

            foreach (var item in _CityData.Hourly.list)
            {
                item.Date = dateTime.AddSeconds(item.dt).ToLocalTime().ToString("ddd, H:mm");
                if (await _icons.TryGetItemAsync(item.weather[0].icon + ".png") != null)
                {
                    item.Image = "ms-appx:///Assets/Icons/" + item.weather[0].icon + ".png";
                }
                else
                {
                    item.Image = "ms-appx:///Assets/Icons/02n.png";
                }

                item.main.temp = Math.Round(item.main.temp, 1);
                item.weather[0].description = char.ToUpper(item.weather[0].description[0]) + item.weather[0].description.Substring(1);
            }

            foreach (var item in _CityData.DailyForecast.list)
            {
                item.temp.min = Math.Round(item.temp.min, 0);
                item.temp.max = Math.Round(item.temp.max, 0);
                item.Day      = dateTime.AddSeconds(item.dt).ToLocalTime().ToString("ddd");
                if (await _icons.TryGetItemAsync(item.weather[0].icon + ".png") != null)
                {
                    item.Image = "ms-appx:///Assets/Icons/" + item.weather[0].icon + ".png";
                }
                else
                {
                    item.Image = "ms-appx:///Assets/Icons/02n.png";
                }

                item.weather[0].description = char.ToUpper(item.weather[0].description[0]) + item.weather[0].description.Substring(1);
            }

            return(_CityData);
        }
Beispiel #16
0
        public static object DateTimeFromBytes(this byte[] bytes)
        {
            var seconds = BitConverter.ToInt32(bytes, 0);

            return(ZeroData.AddSeconds(seconds));
        }
Beispiel #17
0
        private DateTime FromUnixTimeString(string unixTimeString)
        {
            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            return(epoch.AddSeconds(int.Parse(unixTimeString)));
        }
Beispiel #18
0
        private void CreateDataForAllAssets()
        {
            var rando        = new Random();
            var assetNames   = DbEntities.Assets.Select(x => x.AssetID).ToList();
            var eventsToSend = new List <CamxEvent>();

            foreach (var asset in assetNames)
            {
                Console.WriteLine("Begin Generate data for: " + asset);
                var counter                = 0;
                var timeBase               = 60;
                var currTime               = new DateTime(2017, 12, 1);
                List <CamxEvent> events    = new List <CamxEvent>();
                List <string>    csvEvents = new List <string>();
                csvEvents.Add("RowID,ItemInstanceID,PlantID,LineID,AssetID,EventTypeName,TimeStamp");
                var lineName  = DbEntities.Assets.Where(x => x.AssetID == asset).Select(x => x.LineID).FirstOrDefault();
                var plantName = DbEntities.Lines.Where(x => x.LineID == lineName).Select(x => x.PlantID)
                                .FirstOrDefault();

                while (currTime < DateTime.Now)
                {
                    if (counter % 500 == 0)
                    {
                        Console.WriteLine("Asset: " + asset + " is at " + counter + " items.");
                    }
                    var thisTime = currTime.AddSeconds(timeBase + rando.Next(0, 30));
                    currTime = thisTime;
                    var itemStart = new CamxEvent
                    {
                        TimeStamp      = thisTime,
                        ItemInstanceID = Guid.NewGuid(),
                        PlantID        = plantName,
                        LineID         = lineName,
                        AssetID        = asset,
                        EventTypeName  = "ItemWorkStart"
                    };

                    var itemComplete = new CamxEvent
                    {
                        TimeStamp      = thisTime,
                        ItemInstanceID = Guid.NewGuid(),
                        PlantID        = plantName,
                        LineID         = lineName,
                        AssetID        = asset,
                        EventTypeName  = "ItemWorkComplete"
                    };
                    counter += 2;
                    events.Add(itemStart);
                    var itemStartCSV = "," + itemStart.ItemInstanceID + "," + itemStart.PlantID + "," + itemStart.LineID +
                                       "," + itemStart.AssetID + "," + itemStart.EventTypeName + "," +
                                       itemStart.TimeStamp;
                    csvEvents.Add(itemStartCSV);

                    events.Add(itemComplete);
                    var itemCompleteCSV = "," + itemComplete.ItemInstanceID + "," + itemComplete.PlantID + "," + itemComplete.LineID +
                                          "," + itemComplete.AssetID + "," + itemComplete.EventTypeName + "," +
                                          itemComplete.TimeStamp;
                    csvEvents.Add(itemCompleteCSV);
                }
                Console.WriteLine("Sending data to database for: " + asset);
                var fileName = @"C:\Users\lords\Documents\Data\" + asset + ".csv";
                File.WriteAllLines(fileName, csvEvents);
//                using (SqlConnection connection = new SqlConnection(
//                    "Server=tcp:teamsteelcase.database.windows.net,1433;Initial Catalog=SteelcaseDB;Persist Security Info=False;User ID=teamsteelcase;Password=Cargoesvroom!;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;")
//                )
//                {
//                    SqlBulkCopy bulkCopy = new SqlBulkCopy(
//                        connection,
//
//                        SqlBulkCopyOptions.TableLock |
//
//                        SqlBulkCopyOptions.FireTriggers |
//
//                        SqlBulkCopyOptions.UseInternalTransaction,
//
//                        null
//                        );
//                    bulkCopy.DestinationTableName = "dbo.CamxEvent";
//                    connection.Open();
//                    bulkCopy.WriteToServer(events);
//                    connection.Close();
//                }


                //                DbEntities.CamxEvents.AddRange(events);
                //                DbEntities.SaveChanges();
            }
        }
Beispiel #19
0
 /// <summary>
 /// unix时间戳转换成日期
 /// </summary>
 /// <param name="unixTimeStamp">时间戳(秒)</param>
 /// <returns></returns>
 public static DateTime UnixTimestampToDateTime(this DateTime target, long timestamp)
 {
     var start = new DateTime(1970, 1, 1, 0, 0, 0, target.Kind);
     return start.AddSeconds(timestamp);
 }
Beispiel #20
0
    /// <summary>
    /// Get access token based on the type parameter type values.
    /// </summary>
    /// <param name="type">If type value is 0, access token is fetch for authorization code flow
    /// If type value is 2, access token is fetch for authorization code floww based on the exisiting refresh token</param>
    /// <returns>true/false; true if success, else false</returns>
    private bool GetAccessToken(AccessTokenType type)
    {
        Stream postStream = null;

        try
        {
            DateTime   currentServerTime  = DateTime.UtcNow.ToLocalTime();
            WebRequest accessTokenRequest = System.Net.HttpWebRequest.Create(string.Empty + this.endPoint + "/oauth/token");
            accessTokenRequest.Method = "POST";
            string oauthParameters = string.Empty;

            if (type == AccessTokenType.Authorization_Code)
            {
                oauthParameters = "client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&code=" + this.authCode + "&grant_type=authorization_code&scope=MOBO";
            }
            else
            {
                oauthParameters = "grant_type=refresh_token&client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&refresh_token=" + this.refreshToken;
            }

            accessTokenRequest.ContentType = "application/x-www-form-urlencoded";
            UTF8Encoding encoding  = new UTF8Encoding();
            byte[]       postBytes = encoding.GetBytes(oauthParameters);
            accessTokenRequest.ContentLength = postBytes.Length;
            postStream = accessTokenRequest.GetRequestStream();
            postStream.Write(postBytes, 0, postBytes.Length);
            postStream.Close();

            WebResponse accessTokenResponse = accessTokenRequest.GetResponse();
            using (StreamReader accessTokenResponseStream = new StreamReader(accessTokenResponse.GetResponseStream()))
            {
                string access_token_json = accessTokenResponseStream.ReadToEnd();
                JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
                AccessTokenResponse  deserializedJsonObj   = (AccessTokenResponse)deserializeJsonObject.Deserialize(access_token_json, typeof(AccessTokenResponse));
                if (deserializedJsonObj.access_token != null)
                {
                    this.accessToken  = deserializedJsonObj.access_token;
                    this.refreshToken = deserializedJsonObj.refresh_token;

                    DateTime refreshExpiry = currentServerTime.AddHours(this.refreshTokenExpiresIn);

                    Session["mobo_session_accessTokenExpiryTime"] = currentServerTime.AddSeconds(Convert.ToDouble(deserializedJsonObj.expires_in));

                    if (deserializedJsonObj.expires_in.Equals("0"))
                    {
                        int defaultAccessTokenExpiresIn = 100; // In Years
                        Session["mobo_session_accessTokenExpiryTime"] = currentServerTime.AddYears(defaultAccessTokenExpiresIn);
                    }

                    this.refreshTokenExpiryTime = refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString();

                    Session["mobo_session_access_token"] = this.accessToken;

                    this.accessTokenExpiryTime                     = Session["mobo_session_accessTokenExpiryTime"].ToString();
                    Session["mobo_session_refresh_token"]          = this.refreshToken;
                    Session["mobo_session_refreshTokenExpiryTime"] = this.refreshTokenExpiryTime.ToString();
                    Session["mobo_session_appState"]               = "TokenReceived";
                    accessTokenResponseStream.Close();
                    return(true);
                }
                else
                {
                    this.DrawPanelForFailure(statusPanel, "Auth server returned null access token");
                    return(false);
                }
            }
        }
        catch (Exception ex)
        {
            this.DrawPanelForFailure(statusPanel, ex.Message);
        }
        finally
        {
            if (null != postStream)
            {
                postStream.Close();
            }
        }

        return(false);
    }
Beispiel #21
0
        public async Task PatchTimestamp_IntegrationTest()
        {
            string[]     tags                   = { "tag/1", "tag/2", "tag/3", "tag/4", null };
            const string timeseries             = "Heartrate";
            const int    timeSeriesPointsAmount = 128;
            const int    docAmount              = 8_192;

            using (var store = GetDocumentStore())
            {
                await using (var bulkInsert = store.BulkInsert())
                {
                    for (int i = 0; i < docAmount; i++)
                    {
                        await bulkInsert.StoreAsync(new TimeSeriesPatchTests.TimeSeriesResultHolder(), $"TimeSeriesResultHolders/{i}");
                    }
                }

                var baseTime     = new DateTime(2020, 2, 12);
                var randomValues = new Random(2020);
                var toAppend     = Enumerable.Range(0, timeSeriesPointsAmount)
                                   .Select(i =>
                {
                    return(new TimeSeriesEntry
                    {
                        Tag = tags[i % tags.Length],
                        Timestamp = baseTime.AddSeconds(i).AddSeconds(.1 * (randomValues.NextDouble() - .5)),
                        Values = new[] { 256 + 16 * randomValues.NextDouble() }
                    });
                }).ToArray();

                var appendOperation = store
                                      .Operations
                                      .Send(new PatchByQueryOperation(new IndexQuery
                {
                    QueryParameters = new Parameters
                    {
                        { "timeseries", timeseries },
                        { "toAppend", toAppend },
                    },
                    Query = @"
from TimeSeriesResultHolders as c
update
{
    for(var i = 0; i < $toAppend.length; i++){
        timeseries(this, $timeseries).append($toAppend[i].Timestamp, $toAppend[i].Values, $toAppend[i].Tag);
    }
}"
                }));
                await appendOperation.WaitForCompletionAsync();

                var deleteFrom      = toAppend[timeSeriesPointsAmount * 1 / 3].Timestamp;
                var deleteTo        = toAppend[timeSeriesPointsAmount * 3 / 4].Timestamp;
                var deleteOperation = store
                                      .Operations
                                      .Send(new PatchByQueryOperation(new IndexQuery
                {
                    QueryParameters = new Parameters
                    {
                        { "timeseries", timeseries },
                        { "from", deleteFrom },
                        { "to", deleteTo }
                    },
                    Query = @"
from TimeSeriesResultHolders as c
update
{
  timeseries(this, $timeseries).delete($from, $to);
}"
                }));
                await deleteOperation.WaitForCompletionAsync();

                var getFrom      = toAppend[timeSeriesPointsAmount * 1 / 5].Timestamp;
                var getTo        = toAppend[timeSeriesPointsAmount * 4 / 5].Timestamp;
                var getOperation = store
                                   .Operations
                                   .Send(new PatchByQueryOperation(new IndexQuery
                {
                    QueryParameters = new Parameters
                    {
                        { "timeseries", timeseries },
                        { "from", getFrom },
                        { "to", getTo }
                    },
                    Query = @"
from TimeSeriesResultHolders as c
update
{
  this.Result = timeseries(this, $timeseries).get($from, $to);
}"
                }));
                await getOperation.WaitForCompletionAsync();

                using (var session = store.OpenAsyncSession())
                {
                    var docs = await session
                               .Query <TimeSeriesPatchTests.TimeSeriesResultHolder>()
                               .Customize(x => x.WaitForNonStaleResults(TimeSpan.FromSeconds(5)))
                               .ToArrayAsync();

                    foreach (var doc in docs)
                    {
                        var expectedList = toAppend
                                           .Where(s => s.Timestamp >= getFrom && s.Timestamp <= getTo)
                                           .Where(s => s.Timestamp <deleteFrom || s.Timestamp> deleteTo)
                                           .ToArray();

                        Assert.Equal(expectedList.Length, doc.Result.Length);
                        for (int i = 0; i < expectedList.Length; i++)
                        {
                            var expected = expectedList[i];
                            var actual   = doc.Result[i];
                            if (expected.Timestamp < getFrom || expected.Timestamp > getTo)
                            {
                                continue;
                            }
                            if (expected.Timestamp >= deleteFrom || expected.Timestamp <= deleteTo)
                            {
                                continue;
                            }

                            Assert.Equal(expected.Timestamp, actual.Timestamp, RavenTestHelper.DateTimeComparer.Instance);
                            Assert.Equal(expected.Values, actual.Values);
                            Assert.Equal(expected.Tag, actual.Tag);
                        }
                    }
                }
            }
        }
Beispiel #22
0
 public static DateTime?NAddSeconds(this DateTime?self, double?value)
 => value.HasValue ? self?.AddSeconds(value.Value) : null;
Beispiel #23
0
        void DoFetchTweets()
        {
            ulong maxID_favs        = 0;
            ulong maxID_DM_sent     = 0;
            ulong maxID_DM_received = 0;

            List <Favorites>     favsResponse        = new List <Favorites>();
            List <DirectMessage> sentDMsResponse     = new List <DirectMessage>();
            List <DirectMessage> receivedDMsResponse = new List <DirectMessage>();

            while (true)
            {
                if (!isQueryingTwitter)
                {
                    StopProgressStatus();
                    Thread.Sleep(200);
                    continue;
                }

                StartProgressStatus();

                bool shouldContinue = true;
                do
                {
                    if (!isQueryingTwitter)
                    {
                        StopProgressStatus();
                        Thread.Sleep(200);
                        continue;
                    }

                    StartProgressStatus();

                    // Check if we are hitting rate limits
                    if (ReachedTwitterLimits(TweetsEraseType, out RateLimitReset))
                    {
                        RateLimitReset = RateLimitReset.AddSeconds(15); // Add some seconds to avoid querying too soon
                        HandleReachedTwitterLimits();
                        break;
                    }

                    try
                    {
                        switch (TweetsEraseType)
                        {
                        case ApplicationSettings.EraseTypes.TweetsAndRetweets:
                            throw new Exception("EraseTye should never be EraseTypes.TweetsAndRetweets here");

                        case ApplicationSettings.EraseTypes.Favorites:
                            favsResponse.Clear();
                            favsResponse = QueryFavorites(twitterCtx, maxID_favs);
                            break;

                        case ApplicationSettings.EraseTypes.DirectMessages:
                            sentDMsResponse.Clear();
                            receivedDMsResponse.Clear();
                            sentDMsResponse     = QuerySentDMs(twitterCtx, maxID_DM_sent);
                            receivedDMsResponse = QueryReceivedDMs(twitterCtx, maxID_DM_received);
                            break;

                        default:
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        if (twitterCtx.RateLimitRemaining == 0)
                        {
                            HandleReachedTwitterLimits();
                        }
                        else
                        {
                            Dispatcher.BeginInvoke(new Action(delegate()
                            {
                                MessageBox.Show(ex.Message);
                            }));
                        }

                        Unset_QueryingTwitter();
                        break;
                    }

                    // fetched all the favorites
                    bool reachedFavsLimitsOrNoMoreFavs = (favsResponse == null || favsResponse.Count == 0 || favsTweetList.Count == userFavoritesCount);
                    bool noMoreDms = (sentDMsResponse == null || sentDMsResponse.Count == 0) && (receivedDMsResponse == null || receivedDMsResponse.Count == 0);

                    bool isTwitterFavortiesLimitsBug = TweetsEraseType == ApplicationSettings.EraseTypes.Favorites && (favsResponse == null || favsResponse.Count == 0);

                    if ((TweetsEraseType == ApplicationSettings.EraseTypes.Favorites && reachedFavsLimitsOrNoMoreFavs) ||
                        (TweetsEraseType == ApplicationSettings.EraseTypes.DirectMessages && noMoreDms))
                    {
                        lblContinue.Dispatcher.BeginInvoke(new Action(delegate()
                        {
                            lblContinue.Text              = "Done fetching tweets.";
                            lblContinue.Visibility        = System.Windows.Visibility.Visible;
                            stackReachedLimits.Visibility = System.Windows.Visibility.Collapsed;

                            if (isTwitterFavortiesLimitsBug)
                            {
                                lblFailedToGetMoreTweets.Visibility = Visibility.Visible;
                            }
                        }));

                        Unset_QueryingTwitter();
                        break;
                    }

                    // query next batch
                    if (TweetsEraseType == ApplicationSettings.EraseTypes.Favorites)
                    {
                        maxID_favs = favsResponse.Min(fav => fav.StatusID) - 1;
                        favsTweetList.AddRange(favsResponse);
                        UpdateNumFetchedTweets(favsTweetList.Count);

                        shouldContinue = favsResponse.Count > 0;
                    }

                    if (TweetsEraseType == ApplicationSettings.EraseTypes.DirectMessages)
                    {
                        maxID_DM_sent     = sentDMsResponse.Min(dm => dm.IDResponse) - 1;
                        maxID_DM_received = receivedDMsResponse.Min(dm => dm.IDResponse) - 1;

                        dmsTweetList.AddRange(sentDMsResponse);
                        dmsTweetList.AddRange(receivedDMsResponse);

                        UpdateNumFetchedTweets(dmsTweetList.Count);

                        shouldContinue = sentDMsResponse.Count > 0 || receivedDMsResponse.Count > 0;
                    }
                } while (shouldContinue);
            }
        }
        public Level13()
        {
            this.InitializeComponent();

            //set the dispatcherTimer and dateTime ready
            dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
            dispatcherTimer.Tick    += dispatcherTimer_Tick;

            dispatcherTimer2.Interval = TimeSpan.FromSeconds(1);

            //adding the images to a list, makes life easier
            list_images.Add(image1);
            list_images.Add(image2);
            list_images.Add(image3);
            list_images.Add(image4);
            list_images.Add(image5);
            list_images.Add(image6);
            list_images.Add(image7);
            list_images.Add(image8);
            list_images.Add(image9);
            list_images.Add(image10);
            list_images.Add(image11);
            list_images.Add(image12);


            //adding storyboards to a list, also makes life easier
            list_storyboards.Add(stry1a);
            list_storyboards.Add(stry1b);
            list_storyboards.Add(stry2a);
            list_storyboards.Add(stry2b);
            list_storyboards.Add(stry3a);
            list_storyboards.Add(stry3b);
            list_storyboards.Add(stry4a);
            list_storyboards.Add(stry4b);
            list_storyboards.Add(stry5a);
            list_storyboards.Add(stry5b);
            list_storyboards.Add(stry6a);
            list_storyboards.Add(stry6b);
            list_storyboards.Add(stry7a);
            list_storyboards.Add(stry7b);
            list_storyboards.Add(stry8a);
            list_storyboards.Add(stry8b);
            list_storyboards.Add(stry9a);
            list_storyboards.Add(stry9b);
            list_storyboards.Add(stry10a);
            list_storyboards.Add(stry10b);
            list_storyboards.Add(stry11a);
            list_storyboards.Add(stry11b);
            list_storyboards.Add(stry12a);
            list_storyboards.Add(stry12b);

            //make capital letters
            for (int i = 0; i < 12; i++)
            {
                unitsShowns[i] = letters[random.Next(0, 25)];
            }

            //make lowercase letters
            for (int i = 12; i < 24; i++)
            {
                unitsShowns[i] = letters[random.Next(26, 52)];
            }


            //Show letters
            tbkUnitsShowing1.Text  = unitsShowns[0];
            tbkUnitsShowing2.Text  = unitsShowns[1];
            tbkUnitsShowing3.Text  = unitsShowns[2];
            tbkUnitsShowing4.Text  = unitsShowns[3];
            tbkUnitsShowing5.Text  = unitsShowns[4];
            tbkUnitsShowing6.Text  = unitsShowns[5];
            tbkUnitsShowing7.Text  = unitsShowns[6];
            tbkUnitsShowing8.Text  = unitsShowns[7];
            tbkUnitsShowing9.Text  = unitsShowns[8];
            tbkUnitsShowing10.Text = unitsShowns[9];
            tbkUnitsShowing11.Text = unitsShowns[10];
            tbkUnitsShowing12.Text = unitsShowns[11];

            tbkUnitsShowing13.Text = unitsShowns[12];
            tbkUnitsShowing14.Text = unitsShowns[13];
            tbkUnitsShowing15.Text = unitsShowns[14];
            tbkUnitsShowing16.Text = unitsShowns[15];
            tbkUnitsShowing17.Text = unitsShowns[16];
            tbkUnitsShowing18.Text = unitsShowns[17];
            tbkUnitsShowing19.Text = unitsShowns[18];
            tbkUnitsShowing20.Text = unitsShowns[19];
            tbkUnitsShowing21.Text = unitsShowns[20];
            tbkUnitsShowing22.Text = unitsShowns[21];
            tbkUnitsShowing23.Text = unitsShowns[22];
            tbkUnitsShowing24.Text = unitsShowns[23];

            startTimer.Interval = TimeSpan.FromSeconds(1);
            startT           = startT.AddSeconds(5);
            startTimer.Tick += startTimer_Tick;
            startTimer.Start();
        }
Beispiel #25
0
        private static DateTime ConvertFromUnixTimestamp(double timestamp)
        {
            var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);

            return(origin.AddSeconds(timestamp));
        }
Beispiel #26
0
        private static OSD ParseLLSDBinaryElement(Stream stream)
        {
            SkipWhiteSpace(stream);
            OSD osd;

            int marker = stream.ReadByte();

            if (marker < 0)
            {
                throw new OSDException("Binary LLSD parsing: Unexpected end of stream.");
            }

            switch ((byte)marker)
            {
            case undefBinaryValue:
                osd = new OSD();
                break;

            case trueBinaryValue:
                osd = OSD.FromBoolean(true);
                break;

            case falseBinaryValue:
                osd = OSD.FromBoolean(false);
                break;

            case integerBinaryMarker:
                int integer = Utils.BytesToIntBig(ConsumeBytes(stream, int32Length));
                osd = OSD.FromInteger(integer);
                break;

            case realBinaryMarker:
                double dbl = Utils.BytesToDoubleBig(ConsumeBytes(stream, doubleLength));
                osd = OSD.FromReal(dbl);
                break;

            case uuidBinaryMarker:
                osd = OSD.FromUUID(new UUID(ConsumeBytes(stream, 16), 0));
                break;

            case binaryBinaryMarker:
                int binaryLength = Utils.BytesToIntBig(ConsumeBytes(stream, int32Length));
                osd = OSD.FromBinary(ConsumeBytes(stream, binaryLength));
                break;

            case stringBinaryMarker:
                int    stringLength = Utils.BytesToIntBig(ConsumeBytes(stream, int32Length));
                string ss           = Encoding.UTF8.GetString(ConsumeBytes(stream, stringLength));
                osd = OSD.FromString(ss);
                break;

            case uriBinaryMarker:
                int    uriLength = Utils.BytesToIntBig(ConsumeBytes(stream, int32Length));
                string sUri      = Encoding.UTF8.GetString(ConsumeBytes(stream, uriLength));
                Uri    uri;
                try
                {
                    uri = new Uri(sUri, UriKind.RelativeOrAbsolute);
                }
                catch
                {
                    throw new OSDException("Binary LLSD parsing: Invalid Uri format detected.");
                }
                osd = OSD.FromUri(uri);
                break;

            case dateBinaryMarker:
                double   timestamp = Utils.BytesToDouble(ConsumeBytes(stream, doubleLength));
                DateTime dateTime  = DateTime.SpecifyKind(Utils.Epoch, DateTimeKind.Utc);
                dateTime = dateTime.AddSeconds(timestamp);
                osd      = OSD.FromDate(dateTime.ToLocalTime());
                break;

            case arrayBeginBinaryMarker:
                osd = ParseLLSDBinaryArray(stream);
                break;

            case mapBeginBinaryMarker:
                osd = ParseLLSDBinaryMap(stream);
                break;

            default:
                throw new OSDException("Binary LLSD parsing: Unknown type marker.");
            }
            return(osd);
        }
Beispiel #27
0
        public static TdsDateTime FromDateTime(DateTime dateTime, byte cb)
        {
            SqlDateTime sqlDateTime;
            TdsDateTime tdsDateTime = new TdsDateTime();

            Debug.Assert(cb == 8 || cb == 4, "Invalid date time size!");

            if (cb == 8)
            {
                sqlDateTime = new SqlDateTime(dateTime);
                tdsDateTime.time = sqlDateTime.TimeTicks;
            }
            else
            {
                // note that smalldatetime is days&minutes.
                // Adding 30 seconds ensures proper roundup if the seconds are >= 30
                // The AddSeconds function handles eventual carryover
                sqlDateTime = new SqlDateTime(dateTime.AddSeconds(30));
                tdsDateTime.time = sqlDateTime.TimeTicks / SqlDateTime.SQLTicksPerMinute;
            }
            tdsDateTime.days = sqlDateTime.DayTicks;
            return tdsDateTime;
        }
Beispiel #28
0
    public DateTime DateTimeChange(double timestamp)
    {
        DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);

        return(origin.AddSeconds(timestamp));
    }
Beispiel #29
0
            private static DateTime BuiltTime()
            {
                string filePath = System.Reflection.Assembly.GetCallingAssembly().Location;
                const int c_PeHeaderOffset = 60;
                const int c_LinkerTimestampOffset = 8;
                byte[] b = new byte[2048];
                System.IO.Stream s = null;

                try
                {
                    s = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    s.Read(b, 0, 2048);
                }
                finally
                {
                    if (s != null)
                    {
                        s.Close();
                    }
                }

                int i = System.BitConverter.ToInt32(b, c_PeHeaderOffset);
                int secondsSince1970 = System.BitConverter.ToInt32(b, i + c_LinkerTimestampOffset);
                DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                dt = dt.AddSeconds(secondsSince1970);
                dt = dt.ToLocalTime();
                return dt;
            }
Beispiel #30
0
        public List <JiveDEAActivityInstance> GetActivity(List <string> filter = null, int count = 100, List <string> fields = null, DateTime?before = null, DateTime?after = null,
                                                          bool showAll         = false)
        {
            // Jive's DES server seems to off by a few seconds. When making calls using before or after, if either is ahead of the Jive's server, we get a 400 Bad Request Error.
            // For that reason, we push back the these values by 20 seconds. It should be noted that this is problem may get resolved later or not appear on certain clients.
            // Still getting these errors every once in a while, so bumping up to 30 seconds
            before = before?.AddSeconds(-30);
            after  = after?.AddSeconds(-30);

            List <JiveDEAActivityInstance> activityList = new List <JiveDEAActivityInstance>();

            string url = _desUrl + "/activity";

            url += "?count=" + (count > 1000 ? 1000 : count).ToString();
            url += "&show-all=" + showAll;
            if (after != null)
            {
                url += "&after=" + jiveDateFormat(after.Value);
            }
            if (before != null)
            {
                url += "&before=" + jiveDateFormat(before.Value);
            }
            if (fields != null && fields.Count > 0)
            {
                url += "&fields=";
                foreach (var field in fields)
                {
                    url += field + ",";
                }
                // remove last comma
                url = url.Remove(url.Length - 1);
            }
            if (filter != null && filter.Count > 0)
            {
                foreach (var item in filter)
                {
                    url += "&filter=" + item;
                }
            }

            // jive returns a paginated list, so we have to loop through all of the pages.
            while (true)
            {
                string json;
                try
                {
                    json = GetAbsolute(url, getAuthorization());
                }
                catch (HttpException e)
                {
                    switch (e.GetHttpCode())
                    {
                    case 400:
                        throw new HttpException(e.WebEventCode, "An input field is missing or malformed", e);

                    case 403:
                        throw new HttpException(e.WebEventCode, "You are not allowed to access this", e);

                    case 401:     // If the token happens to have expired, try once more before giving up.
                        json = retry(url);
                        break;

                    default:
                        throw;
                    }
                }
                JObject results = JObject.Parse(json);

                activityList.AddRange(results["list"].ToObject <List <JiveDEAActivityInstance> >());
                if (!results.ToString().Contains("paging"))
                {
                    throw new HttpException($"DESClient returned unexpected json, may be down. Invalid Json: {results.ToString()}");
                }
                else if (results["paging"] == null || results["paging"]["next"] == null)
                {
                    break;
                }
                else
                {
                    url = results["paging"]["next"].ToString();
                }
            }
            return(activityList);
        }
Beispiel #31
0
        public static joystickaxis getMovingAxis(string name, int threshold)
        {
            var joystick = new Joystick().AcquireJoystick(name);

            if (joystick == null)
            {
                return(joystickaxis.ARx);
            }

            joystick.Poll();

            System.Threading.Thread.Sleep(300);

            joystick.Poll();

            var       obj    = joystick.CurrentJoystickState();
            Hashtable values = new Hashtable();

            // get the state of the joystick before.
            Type type = obj.GetType();

            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                values[property.Name] = int.Parse(property.GetValue(obj, null).ToString());
            }
            values["Slider1"] = obj.GetSlider()[0];
            values["Slider2"] = obj.GetSlider()[1];
            values["Hatud1"]  = obj.GetPointOfView()[0];
            values["Hatlr2"]  = obj.GetPointOfView()[0];
            values["Custom1"] = 0;
            values["Custom2"] = 0;

            CustomMessageBox.Show("Please move the joystick axis you want assigned to this function after clicking ok");

            DateTime start = DateTime.Now;

            while (start.AddSeconds(10) > DateTime.Now)
            {
                joystick.Poll();
                System.Threading.Thread.Sleep(50);
                var nextstate = joystick.CurrentJoystickState();

                int[] slider = nextstate.GetSlider();

                int[] hat1 = nextstate.GetPointOfView();

                type       = nextstate.GetType();
                properties = type.GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    //Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));

                    log.InfoFormat("test name {0} old {1} new {2} ", property.Name, values[property.Name],
                                   int.Parse(property.GetValue(nextstate, null).ToString()));
                    log.InfoFormat("{0}  {1} {2}", property.Name, (int)values[property.Name],
                                   (int.Parse(property.GetValue(nextstate, null).ToString()) + threshold));
                    if ((int)values[property.Name] >
                        (int.Parse(property.GetValue(nextstate, null).ToString()) + threshold) ||
                        (int)values[property.Name] <
                        (int.Parse(property.GetValue(nextstate, null).ToString()) - threshold))
                    {
                        log.Info(property.Name);
                        joystick.Unacquire();
                        return((joystickaxis)Enum.Parse(typeof(joystickaxis), property.Name));
                    }
                }

                // slider1
                if ((int)values["Slider1"] > (slider[0] + threshold) ||
                    (int)values["Slider1"] < (slider[0] - threshold))
                {
                    joystick.Unacquire();
                    return(joystickaxis.Slider1);
                }

                // slider2
                if ((int)values["Slider2"] > (slider[1] + threshold) ||
                    (int)values["Slider2"] < (slider[1] - threshold))
                {
                    joystick.Unacquire();
                    return(joystickaxis.Slider2);
                }

                // Hatud1
                if ((int)values["Hatud1"] != (hat1[0]))
                {
                    joystick.Unacquire();
                    return(joystickaxis.Hatud1);
                }

                // Hatlr2
                if ((int)values["Hatlr2"] != (hat1[0]))
                {
                    joystick.Unacquire();
                    return(joystickaxis.Hatlr2);
                }
            }

            CustomMessageBox.Show("No valid option was detected");

            return(joystickaxis.None);
        }
Beispiel #32
0
 // Picks a random time in the last year
 static public DateTime PickDateTime()
 {
     return(base_time.AddSeconds(-random.Next(seconds_per_year)));
 }
Beispiel #33
0
 public static DateTime ToDateTime(this uint timestamp)
 {
     return(unixEpoch.AddSeconds(timestamp).ToLocalTime());
 }
Beispiel #34
0
        //public static double[] GetBollingerBandsWithSimpleMovingAverage(this IList<IMarketChartData> value, int index, int period = 20)
        //{
        //    var closes = new List<double>(period);
        //    for (var i = index; i > Math.Max(index - period, -1); i--)
        //    {
        //        closes.Add(value[i].Close);
        //    }

        //    var simpleMovingAverage = closes.Average();
        //    var stDevMultiplied = Math.Sqrt(closes.Average(x => Math.Pow(x - simpleMovingAverage, 2))) * 2;

        //    return new[] {
        //        simpleMovingAverage,
        //        simpleMovingAverage + stDevMultiplied,
        //        simpleMovingAverage - stDevMultiplied
        //    };
        //}

        internal static DateTime UnixTimeStampToDateTime(ulong unixTimeStamp)
        {
            return(DateTimeUnixEpochStart.AddSeconds(unixTimeStamp));
        }
Beispiel #35
0
        public void CanAddSecondsAcrossDstTransition()
        {
            var tz = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
            var dt = new DateTime(2015, 3, 8, 1, 59, 59);
            var result = dt.AddSeconds(1, tz);

            var expected = new DateTimeOffset(2015, 3, 8, 3, 0, 0, TimeSpan.FromHours(-7));
            Assert.Equal(expected, result);
            Assert.Equal(expected.Offset, result.Offset);
        }
Beispiel #36
0
 private static DateTime FromUnixTime(long totalSeconds)
 {
     return(EpochDate.AddSeconds(totalSeconds));
 }
Beispiel #37
0
        internal static RateLimitInfo?FromHttp(HttpResponseMessage resp)
        {
            int      _remaining;
            DateTime?_reset = null;
            int      _total;

            if (resp.Headers.TryGetValues("Rate-Limit-Remaining", out IEnumerable <string> remainings))
            {
                string val = remainings.FirstOrDefault();
                if (val != null)
                {
                    if (int.TryParse(val, out int result))
                    {
                        _remaining = result;
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }

            if (resp.Headers.TryGetValues("Rate-Limit-Total", out IEnumerable <string> totals))
            {
                string val = totals.FirstOrDefault();
                if (val != null)
                {
                    if (int.TryParse(val, out int result))
                    {
                        _total = result;
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }

            if (resp.Headers.TryGetValues("Rate-Limit-Reset", out IEnumerable <string> resets))
            {
                string val = resets.FirstOrDefault();
                if (val != null)
                {
                    if (ulong.TryParse(val, out ulong ts))
                    {
                        _reset = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                        _reset = _reset?.AddSeconds(ts).ToLocalTime();
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            else
            {
                return(null);
            }

            if (_reset == null)
            {
                return(null);
            }
            return(new RateLimitInfo(_remaining, (DateTime)_reset, _total));
        }
Beispiel #38
0
 public static DateTime DateFromUnixTime(this long unixTime)
 {
     var dt = new DateTime(1970, 1, 1, 1, 0, 0, 0, 0);
     return dt.AddSeconds(unixTime).ToLocalTime();
 }