Provides extension methods for DateTime.
예제 #1
0
        public void GetInteger()
        {
            var timestamp = DateTimeExtensions.ToMillisecondInt64(Time);

            Assert.Equal(LongTimestamp, timestamp);
        }
예제 #2
0
        public void Should_set_the_expiry_header_to_a_absolute_utc_time()
        {
            RegisterMessageType <DeferredMessage>();
            var time = DateTime.Now + TimeSpan.FromDays(1);

            bus.Defer(time, new DeferredMessage());

            VerifyThatMessageWasSentWithHeaders(h => h[TimeoutManagerHeaders.Expire] == DateTimeExtensions.ToWireFormattedString(time));
        }
예제 #3
0
        public static VkMessage FromJson(JToken json, string apiVersion = null)
        {
            if (json == null)
            {
                throw new Exception("Json can't be null");
            }

            var result = new VkMessage();

            if (json["id"] != null)
            {
                result.Id = (long)json["id"];
            }

            if (json["user_id"] != null)
            {
                result.UserId = (long)json["user_id"];
            }
            result.Date = DateTimeExtensions.UnixTimeStampToDateTime((long)json["date"]);

            if (json["read_state"] != null)
            {
                result.IsRead = (int)json["read_state"] == 1;
            }

            if (json["out"] != null)
            {
                result.IsOut = (int)json["out"] == 1;
            }

            result.Title = (string)json["title"];
            result.Body  = (string)json["body"];

            if (json["deleted"] != null)
            {
                result.IsDeleted = (int)json["deleted"] == 1;
            }

            if (json["attachments"] != null)
            {
                result.Attachments = VkAttachment.FromJson(json["attachments"]);
            }

            if (json["geo"] != null)
            {
                result.Geo = VkGeo.FromJson(json["geo"]);
            }

            if (json["fwd_messages"] != null)
            {
                result.ForwardMessages = new List <VkMessage>();
                foreach (var fwdMessage in json["fwd_messages"])
                {
                    var message = VkMessage.FromJson(fwdMessage);
                    result.ForwardMessages.Add(message);
                }
            }

            if (json["emoji"] != null)
            {
                result.ContainsEmoji = (int)json["emoji"] == 1;
            }

            if (json["chat_id"] != null)
            {
                result.ChatId = (long)json["chat_id"];
            }

            if (json["chat_active"] != null)
            {
                result.ChatUsers = json["chat_active"].Select(t => t.Value <long>()).ToList();
            }

            if (json["users_count"] != null)
            {
                result.UsersCount = (int)json["users_count"];
            }

            if (json["admin_id"] != null)
            {
                result.AdminId = (long)json["admin_id"];
            }

            if (json["action"] != null)
            {
                result.Action = (string)json["action"];
            }

            if (json["action_text"] != null)
            {
                result.ActionText = (string)json["action_text"];
            }

            if (json["photo_50"] != null)
            {
                result.Photo50 = (string)json["photo_50"];
            }

            if (json["photo_100"] != null)
            {
                result.Photo100 = (string)json["photo_100"];
            }

            if (json["photo_200"] != null)
            {
                result.Photo200 = (string)json["photo_200"];
            }

            return(result);
        }
예제 #4
0
        public static VkLongPollMessage FromJson(JArray json)
        {
            var result = new VkLongPollMessage();

            result.Parameters = new Dictionary <string, object>();

            var messageType = json[0].Value <string>();

            switch (messageType)
            {
            //удаление сообщения с указанным local_id
            case "0":
                result.Type = VkLongPollMessageType.MessageDelete;
                result.Parameters.Add("message_id", json[1].Value <string>());
                break;

            //замена флагов сообщения
            case "1":
                result.Type = VkLongPollMessageType.MessageFlagUpdate;
                result.Parameters.Add("message_id", json[1].Value <string>());
                result.Parameters.Add("flags", json[2].Value <VkLongPollMessageFlags>());
                break;

            //установка флагов сообщения
            case "2":
                result.Type = VkLongPollMessageType.MessageFlagSet;
                result.Parameters.Add("message_id", json[1].Value <string>());
                result.Parameters.Add("flags", json[2].Value <int>());
                if (json.Count > 2)
                {
                    result.Parameters.Add("user_id", json[3].Value <long>());
                }
                break;

            //сброс флагов сообщения
            case "3":
                result.Type = VkLongPollMessageType.MessageFlagReset;
                result.Parameters.Add("message_id", json[1].Value <string>());
                result.Parameters.Add("flags", json[2].Value <int>());
                if (json.Count > 2)
                {
                    result.Parameters.Add("user_id", json[3].Value <long>());
                }
                break;

            //добавление нового сообщения
            case "4":
                result.Type = VkLongPollMessageType.MessageAdd;
                var m = new VkMessage();
                m.Id = json[1].Value <long>();
                var flags = json[2].Value <int>();
                var uid   = json[3].Value <long>();
                if (uid >= ChatIdMask)
                {
                    //беседа
                    result.Parameters.Add("conversation", "1");
                    m.ChatId = (uid - ChatIdMask);
                }
                else
                {
                    m.UserId = uid;
                }

                m.Date  = DateTimeExtensions.UnixTimeStampToDateTime(json[4].Value <double>()).ToLocalTime();
                m.Title = json[5].Value <string>();
                m.Body  = json[6].Value <string>();
                result.Parameters.Add("message", m);
                result.Parameters.Add("flags", flags);

                if (json[7] != null)
                {
                    //attachments

                    try
                    {
                        var longPollAttachments = new List <VkLongPollAttachment>();

                        var dict = json[7].Value <JObject>().Properties().ToDictionary(p => p.Name, p => p.Value.Value <string>());

                        foreach (var o in dict)
                        {
                            var id = o.Key.Replace("_type", string.Empty);

                            VkLongPollAttachment longPollAttachment = longPollAttachments.FirstOrDefault(a => a.Id == id);
                            if (longPollAttachment == null)
                            {
                                longPollAttachment = new VkLongPollAttachment()
                                {
                                    Id = id
                                };
                                longPollAttachments.Add(longPollAttachment);
                            }

                            if (o.Key.EndsWith("_type"))
                            {
                                longPollAttachment.Type = o.Value;
                            }
                            else
                            {
                                if (o.Key == "geo")     //special attachment
                                {
                                    longPollAttachment.Type = "geo";
                                }
                                else if (o.Key == "fwd")
                                {
                                    longPollAttachment.Type = "fwd";
                                }
                                else if (o.Key == "from")
                                {
                                    m.UserId = long.Parse(o.Value);
                                }


                                longPollAttachment.Data = o.Value;
                            }
                        }

                        if (longPollAttachments.Count > 0)
                        {
                            m.Attachments = new List <VkAttachment>(longPollAttachments.Count);

                            foreach (var longPollAttachment in longPollAttachments)
                            {
                                if (longPollAttachment.Type == "geo")
                                {
                                    //not an attachment for message
                                    //requires reverse geocoding
                                    m.Geo = new VkGeo();
                                }
                                else if (longPollAttachment.Id == "fwd_msg_count")
                                {
                                    //adding placeholder messages, client app will reload message to get it
                                    int count = int.Parse(longPollAttachment.Data);
                                    m.ForwardMessages = new List <VkMessage>();
                                    for (int i = 0; i < count; i++)
                                    {
                                        m.ForwardMessages.Add(new VkMessage());
                                    }
                                }
                                else if (longPollAttachment.Type == "sticker")
                                {
                                    var sticker = new VkStickerAttachment();

                                    sticker.ProductId = long.Parse(longPollAttachment.Data);
                                    sticker.Photo256  = "http://vk.com/images/stickers/" + sticker.ProductId + "/256.png";
                                    m.Attachments.Add(sticker);
                                }
                                else
                                {
                                    var a = longPollAttachment.ToAttachment();
                                    if (a != null)
                                    {
                                        m.Attachments.Add(a);
                                    }
                                    else
                                    {
                                        Debug.WriteLine("Unable to parse attachment " + a);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("Unable to parse attachments of LongPollMessage. " + ex);
                    }
                }
                break;

            //друг стал онлайн
            case "8":
                result.Type = VkLongPollMessageType.FriendOnline;
                result.Parameters.Add("user_id", json[1].Value <string>().Substring(1));
                break;

            //друг стал оффлайн
            case "9":
                result.Type = VkLongPollMessageType.FriendOffline;
                result.Parameters.Add("user_id", json[1].Value <string>().Substring(1));
                break;

            //один из параметров (состав, тема) беседы был изменен
            case "51":
                result.Type = VkLongPollMessageType.ConversationChange;
                result.Parameters.Add("chat_id", json[1].Value <string>());
                result.Parameters.Add("self", json[2].Value <string>() == "1");
                break;

            //пользователь начал набирать текст в диалоге
            case "61":
                result.Type = VkLongPollMessageType.DialogUserTyping;
                result.Parameters.Add("user_id", json[1].Value <long>());
                break;

            //пользователь начал набирать текст в беседе
            case "62":
                result.Type = VkLongPollMessageType.ConsersationUserTyping;
                result.Parameters.Add("user_id", json[1].Value <long>());
                result.Parameters.Add("chat_id", json[2].Value <long>());
                break;

            default:
                result.Type = VkLongPollMessageType.Unknown;
                break;
            }

            return(result);
        }
예제 #5
0
        public TimeSpan ToTimeSpan(object a)
        {
            if (a == null)
            {
                return(default(TimeSpan));
            }
            Type type;

            if (a is IValue)
            {
                type = ((IValue)a).Type;
                a    = ((IValue)a).ValueAsObject();
            }
            else
            {
                type = a.GetNumericType();
            }
            if (type == typeof(Int32))
            {
                return(TimeSpan.FromSeconds((Int32)a));
            }
            if (type == typeof(Int64))
            {
                return(TimeSpan.FromSeconds((Int64)a));
            }
            if (type == typeof(Int16))
            {
                return(TimeSpan.FromSeconds((Int16)a));
            }
            if (type == typeof(Char))
            {
                return(TimeSpan.FromSeconds((Char)a));
            }
            if (type == typeof(UInt32))
            {
                return(TimeSpan.FromSeconds((UInt32)a));
            }
            if (type == typeof(UInt64))
            {
                return(TimeSpan.FromSeconds((UInt64)a));
            }
            if (type == typeof(UInt16))
            {
                return(TimeSpan.FromSeconds((UInt16)a));
            }
            if (type == typeof(Byte))
            {
                return(TimeSpan.FromSeconds((Byte)a));
            }
            if (type == typeof(Double))
            {
                return(TimeSpan.FromSeconds((Double)a));
            }
            if (type == typeof(Single))
            {
                return(TimeSpan.FromSeconds((Single)a));
            }
            if (type == typeof(Decimal))
            {
                return(TimeSpan.FromSeconds(ToDouble((Decimal)a)));
            }
            if (type == typeof(DateTime))
            {
                return(DateTimeExtensions.TimeSince1970((DateTime)a));
            }
            return(default(TimeSpan));
        }
 public static String GetNewRoleSessionName()
 {
     return("aliyun-net-sdk-" + DateTimeExtensions.currentTimeMillis(DateTime.Now));
 }
        void Defer(TimeSpan defer, TransportMessage message)
        {
            var retryMessageAt = DateTime.UtcNow + defer;

            TransportMessageHelpers.SetHeader(message, Headers.Retries, (TransportMessageHelpers.GetNumberOfRetries(message) + 1).ToString());

            var addressOfFaultingEndpoint = TransportMessageHelpers.GetAddressOfFaultingEndpoint(message);

            if (!TransportMessageHelpers.HeaderExists(message, SecondLevelRetriesHeaders.RetriesTimestamp))
            {
                TransportMessageHelpers.SetHeader(message, SecondLevelRetriesHeaders.RetriesTimestamp, DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow));
            }

            Logger.DebugFormat("Defer message and send it to {0}", addressOfFaultingEndpoint);

            MessageDeferrer.Defer(message, retryMessageAt, addressOfFaultingEndpoint);
        }
 public void NullableFullMillisecondsWithTimeSpan()
 {
     Assert.AreEqual(1000, DateTimeExtensions.FullMilliseconds(new TimeSpan?(new TimeSpan(0, 0, 1))));
 }
예제 #9
0
        public bool ImportPositions(ExcelPackage package)
        {
            ImportRepo importRepo = new ImportRepo();

            try
            {
                using (package) //new ExcelPackage(new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), "ImportPositions.xlsx"))))
                {
                    ExcelWorksheet     workSheet    = package.Workbook.Worksheets[0];
                    int                totalRows    = workSheet.Dimension.Rows;
                    DateTime           today        = DateTime.Today;
                    List <ImportModel> PositionList = new List <ImportModel>();


                    for (int i = 2; i <= totalRows; i++)
                    {
                        if (workSheet.Cells[i, 1].Text != "")
                        {
                            var dateInput = int.TryParse(workSheet.Cells[i, 19].Text.ToString(), out int n) ? workSheet.Cells[i, 19].Value.ToString() : workSheet.Cells[i, 19].Text.ToString();

                            var dateInput2 = int.TryParse(workSheet.Cells[i, 20].Text.ToString(), out int k) ? workSheet.Cells[i, 20].Value.ToString() : workSheet.Cells[i, 20].Text.ToString();

                            DateTime?dateValue = DateTimeExtensions.ParseDate(dateInput);

                            if (dateValue == null)
                            {
                                return(false);
                            }
                            DateTime?dateValue2 = DateTimeExtensions.ParseDate(dateInput2);


                            if (dateValue2 == null)
                            {
                                return(false);
                            }



                            PositionList.Add(new ImportModel
                            {
                                MPLID           = Convert.ToInt32(workSheet.Cells[i, 1].Value),
                                Season          = string.IsNullOrEmpty(workSheet.Cells[i, 2].Text) ? null : workSheet.Cells[i, 2].Value.ToString(),
                                Region          = string.IsNullOrEmpty(workSheet.Cells[i, 3].Text) ? null : workSheet.Cells[i, 3].Value.ToString(),
                                Country         = string.IsNullOrEmpty(workSheet.Cells[i, 4].Text) ? null : workSheet.Cells[i, 4].Value.ToString(),
                                HeadOf          = string.IsNullOrEmpty(workSheet.Cells[i, 5].Text) ? null : workSheet.Cells[i, 5].Value.ToString(),
                                SDD_DM          = string.IsNullOrEmpty(workSheet.Cells[i, 6].Text) ? null : workSheet.Cells[i, 6].Value.ToString(),
                                Destination     = string.IsNullOrEmpty(workSheet.Cells[i, 7].Text) ? null : workSheet.Cells[i, 7].Value.ToString(),
                                IATACode        = string.IsNullOrEmpty(workSheet.Cells[i, 8].Text) ? null : workSheet.Cells[i, 8].Value.ToString(),
                                ConceptHotel    = string.IsNullOrEmpty(workSheet.Cells[i, 9].Text) ? null : workSheet.Cells[i, 9].Value.ToString(),
                                JobFamily       = string.IsNullOrEmpty(workSheet.Cells[i, 10].Text) ? null : workSheet.Cells[i, 10].Value.ToString(),
                                JobTitle        = string.IsNullOrEmpty(workSheet.Cells[i, 11].Text) ? null : workSheet.Cells[i, 11].Value.ToString(),
                                Profile         = string.IsNullOrEmpty(workSheet.Cells[i, 12].Text) ? null : workSheet.Cells[i, 12].Value.ToString(),
                                MPL_DL_Required = string.IsNullOrEmpty(workSheet.Cells[i, 13].Text) ? null : workSheet.Cells[i, 13].Value.ToString(),
                                MPLPositionType = string.IsNullOrEmpty(workSheet.Cells[i, 14].Text) ? null : workSheet.Cells[i, 14].Value.ToString(),
                                ProcentWorkTime = string.IsNullOrEmpty(workSheet.Cells[i, 15].Text) ? null : workSheet.Cells[i, 15].Value.ToString(),
                                MPLSourceMarket = string.IsNullOrEmpty(workSheet.Cells[i, 16].Text) ? null : workSheet.Cells[i, 16].Value.ToString(),
                                Languages       = string.IsNullOrEmpty(workSheet.Cells[i, 17].Text) ? null : workSheet.Cells[i, 17].Value.ToString(),
                                HighSeason      = string.IsNullOrEmpty(workSheet.Cells[i, 18].Text) ? null : workSheet.Cells[i, 18].Value.ToString(),

                                PositionStartDate = dateValue,
                                PositionEndDate   = dateValue2,


                                MPLDateCreated  = string.IsNullOrEmpty(workSheet.Cells[i, 21].Text) ? null : workSheet.Cells[i, 21].Value.ToString(),
                                FTE             = string.IsNullOrEmpty(workSheet.Cells[i, 22].Text) ? null : workSheet.Cells[i, 22].Value.ToString(),
                                MPLDateModified = string.IsNullOrEmpty(workSheet.Cells[i, 23].Text) ? null : workSheet.Cells[i, 23].Value.ToString(),

                                DateModified = today
                            });
                        }
                        importRepo.ImportPosistions(PositionList);
                    }
                    return(true);
                }
            }
            catch (Exception e)
            {
                Console.Write(e);
                return(false);
            }
        }
        public void SinceUnixTimeTestNullableOffset()
        {
            var baseOffset = new DateTimeOffset?(new DateTimeOffset(1970, 1, 2, 0, 0, 0, new TimeSpan(0)));

            Assert.AreEqual(baseOffset - new DateTime(1970, 1, 1), DateTimeExtensions.SinceUnixTime(baseOffset));
        }
 public void NullableFullMillisecondsWithNull()
 {
     Assert.IsNull(DateTimeExtensions.FullMilliseconds(null));
 }
        public void SinceUnixTimeTestNullableDateTime()
        {
            var baseDT = new DateTime?(new DateTime(1970, 1, 2));

            Assert.AreEqual(1.0d, DateTimeExtensions.SinceUnixTime(baseDT).Value.TotalDays);
        }
        public void SinceUnixTimeTestDate()
        {
            var baseTime = new DateTime(1970, 1, 2);

            Assert.AreEqual(1.0d, DateTimeExtensions.SinceUnixTime(baseTime).TotalDays);
        }
예제 #14
0
        private List <ContactToRemindWithItems> GetReocurringContacts()
        {
            // General VAR definitions
            List <ContactToRemindWithItems> _ContactsToRemind = new List <ContactToRemindWithItems>();
            TrackerTools _TrackerTools = new classes.TrackerTools(); // . from TrackerDotNet.classes.
            DateTime     _dtTemp       = DateTime.MinValue;
            DateTime     _dtNextRoast  = DateTime.MinValue;

            // get the syustem minimum date for if we are closed
            SysDataTbl _SysData = new SysDataTbl();
            DateTime   _MinDate = _SysData.GetMinReminderDate();

            // 1.
            // make sure the dates in the Reoccuring table match the last delivery date
            ReoccuringOrderDAL _ReoccuringOrderDAL = new ReoccuringOrderDAL();

            // Need to add this to the classs
            if (!_ReoccuringOrderDAL.SetReoccuringItemsLastDate())
            {
                showMessageBox _smb = new showMessageBox(this.Page, "Set Reoccuring Item Last Date", "Could not set the re-occuring last date");
                return(_ContactsToRemind);
            }
            // if we get here we could set the last date  ??????????????

            /* 2. For each enabled record in the ReoccuringTbl:
             *   if the LastDatePerItem + DateAdd(ReocurranceType) < NextCityDeliveryDate
             *     then add them into the temporary reminder table, but set the value in the tempoary reminder table to remember that it is a reoccuring and an auto fulfil.
             */

            // now make sure that only records the are enbabled and need to be added from Reoccuring Are added
            List <ReoccuringOrderExtData> _ReoccuringOrders = _ReoccuringOrderDAL.GetAll(ReoccuringOrderDAL.CONST_ENABLEDONLY, "CustomersTbl.CustomerID"); // -1 is all re

            ///////////// perhaps we should return all details in the above query?
            for (int i = 0; i < _ReoccuringOrders.Count; i++)
            {
                switch (_ReoccuringOrders[i].ReoccuranceTypeID)
                {
                case ReoccuranceTypeTbl.CONST_WEEKTYPEID:
                    _ReoccuringOrders[i].NextDateRequired = _ReoccuringOrders[i].DateLastDone.AddDays(_ReoccuringOrders[i].ReoccuranceValue * 7).Date;
                    break;

                case ReoccuranceTypeTbl.CONST_DAYOFMONTHID:
                    _ReoccuringOrders[i].NextDateRequired = _ReoccuringOrders[i].DateLastDone.AddMonths(1).Date;
                    _ReoccuringOrders[i].NextDateRequired = new DateTime(_ReoccuringOrders[i].NextDateRequired.Year, _ReoccuringOrders[i].NextDateRequired.Month, _ReoccuringOrders[i].ReoccuranceValue).Date;
                    break;

                default:
                    break; // not a type we know so exit
                }
                // disable the order if this is the last time
                if ((_ReoccuringOrders[i].RequireUntilDate > TrackerTools.STATIC_TrackerMinDate) && (_ReoccuringOrders[i].NextDateRequired > _ReoccuringOrders[i].RequireUntilDate))
                {
                    _ReoccuringOrders[i].Enabled = false;
                }

                _dtNextRoast = _TrackerTools.GetNextRoastDateByCustomerID(_ReoccuringOrders[i].CustomerID, ref _dtTemp);
                // check if the the Next roast date is less than the system Minimum date
                if (_dtNextRoast < _MinDate)
                {
                    _dtNextRoast = _MinDate;
                }
                // if DateNext < NextDeliveryDate for client the add to list
                if (_ReoccuringOrders[i].NextDateRequired <= _dtNextRoast)
                {
                    // we have a winner we need to add this item but first check if there is an order for this item type.
                    OrderCheck            _orderCheck    = new OrderCheck();
                    List <OrderCheckData> _OrdersToCheck = _orderCheck.GetSimilarItemInOrders(_ReoccuringOrders[i].CustomerID, _ReoccuringOrders[i].ItemRequiredID,
                                                                                              DateTimeExtensions.GetFirstDayOfWeek(_dtNextRoast),
                                                                                              DateTimeExtensions.GetLastDayOfWeek(_dtNextRoast));
                    if (_OrdersToCheck == null)
                    {
                        // there are no orders that have the same item type

                        ItemContactRequires _ItemRequired = new ItemContactRequires();

                        _ItemRequired.CustomerID   = _ReoccuringOrders[i].CustomerID;
                        _ItemRequired.AutoFulfill  = false; // it is a reoccuring order not auto ff
                        _ItemRequired.ReoccurID    = _ReoccuringOrders[i].ReoccuringOrderID;
                        _ItemRequired.ReoccurOrder = true;  // remember it is from reoccuring
                        _ItemRequired.ItemID       = _ReoccuringOrders[i].ItemRequiredID;
                        _ItemRequired.ItemQty      = _ReoccuringOrders[i].QtyRequired;
                        _ItemRequired.ItemPackagID = _ReoccuringOrders[i].PackagingID;

                        // check if the customer exists
                        if (!_ContactsToRemind.Exists(x => x.CustomerID == _ItemRequired.CustomerID))
                        {
                            ContactToRemindWithItems _ContactToRemind = new ContactToRemindWithItems();
                            _ContactToRemind = _ContactToRemind.GetCustomerDetails(_ItemRequired.CustomerID);
                            _ContactToRemind.ItemsContactRequires.Add(_ItemRequired);
                            _ContactsToRemind.Add(_ContactToRemind);
                        }
                        else
                        {
                            int _ContactIdx = _ContactsToRemind.FindIndex(x => x.CustomerID == _ItemRequired.CustomerID);
                            _ContactsToRemind[_ContactIdx].ItemsContactRequires.Add(_ItemRequired);
                        }
                    }
                    else
                    {
                        List <OrderCheckData> _OrderCheckData = null;
                        // store that and order has identified
                        if (Session[CONST_SESSIONVAR_EXISTINGORDERS] == null)
                        {
                            _OrderCheckData = new List <OrderCheckData>();
                        }
                        else
                        {
                            _OrderCheckData = (List <OrderCheckData>)Session[CONST_SESSIONVAR_EXISTINGORDERS];
                        }

                        for (int j = 0; j < _OrdersToCheck.Count; j++)
                        {
                            _OrderCheckData.Add(_OrdersToCheck[j]);
                        }

//            this.gvReminderOfOrdersPlaced.DataSource = _OrderCheckData;
//            this.gvReminderOfOrdersPlaced.DataBind();
//            Session[CONST_SESSIONVAR_EXISTINGORDERS] = _OrderCheckData;
                    }
                } /// we found an item in reoccuring that we need to send a reminder too
            }

            return(_ContactsToRemind);
        }
예제 #15
0
        private static DateTime GetGenDate(XDocument doc, out string rawGenDate)
        {
            rawGenDate = doc.Root.Element("identity").Element("generation").Attribute("date").Value;

            return(DateTimeExtensions.ParseISO8601DateTime(rawGenDate));
        }
 public static DateTime TimeSent(this IInvokeHandlerContext context)
 {
     return(DateTimeExtensions.ToUtcDateTime(context.Headers[Headers.TimeSent]));
 }
예제 #17
0
        public FailureDetails ParseFailureDetails(IReadOnlyDictionary <string, string> headers)
        {
            var result = new FailureDetails();

            DictionaryExtensions.CheckIfKeyExists("NServiceBus.TimeOfFailure", headers, s => result.TimeOfFailure = DateTimeExtensions.ToUtcDateTime(s));

            result.Exception = GetException(headers);

            result.AddressOfFailingEndpoint = headers[FaultsHeaderKeys.FailedQ];

            return(result);
        }
예제 #18
0
        public IActionResult Get(int id)
        {
            try
            {
                var q = (from emp in _context.Employees
                         join contact in _context.Contacts on emp.ContactId equals contact.Id
                         join empType in _context.EmployeeTypes on emp.EmployeeTypeId equals empType.Id
                         join designation in _context.Designations on emp.DesignationId equals designation.Id
                         join status in _context.EmployeeStatuses on emp.EmployeeStatusId equals status.Id
                         where emp.Id == id && status.Code != Constants.DELETED
                         select new EmployeeDetailDto
                {
                    Id = emp.Id,
                    FirstName = contact.FirstName,
                    LastName = contact.LastName,
                    Email = contact.Email,
                    OfficialEmail = contact.OfficialEmail,
                    Phone = contact.Phone,
                    MobilePhone = contact.MobilePhone,
                    IsUnderProbation = emp.IsUnderProbation,
                    EndedProbationAt = DateTimeExtensions.GetFormattedDateString(emp.EndedProbationAt),
                    HiredAt = DateTimeExtensions.GetFormattedDateString(emp.HiredAt),
                    LeaveAt = DateTimeExtensions.GetFormattedDateString(emp.LeaveAt),
                    EmployeeType = empType.Name,
                    Designation = designation.Name,
                    EmployeeStatus = status.Code.ToUpper(),
                    DesignationId = designation.Id,
                    EmployeeStatusId = status.Id,
                    EmployeeTypeId = empType.Id,
                    ABAAccountName = emp.ABAAccountName,
                    ABAAccountNumber = emp.ABAAccountNumber,
                    Remarks = emp.Remarks,
                    Street = contact.PhysicalStreet,
                    City = contact.PhysicalCity,
                    State = contact.PhysicalState,
                    ZipCode = contact.PhysicalZipCode,
                    Country = contact.PhysicalCountry,
                    Address = StringExtensions.ConvertStringArrayToStringJoin(Helpers.AddressParts(
                                                                                  new PhysicalAddress()
                    {
                        Street = contact.PhysicalStreet,
                        City = contact.PhysicalCity,
                        State = contact.PhysicalState,
                        ZipCode = contact.PhysicalZipCode,
                        Country = contact.PhysicalCountry
                    }), ", "),
                    StatusColorClassName = Helpers.AssignStatusColorClassName(status.Code),
                    EmployeeTypeColorClassName = Helpers.AssignEmployeeTypeColorClassName(empType.Name)
                }).FirstOrDefault();

                if (q == null)
                {
                    return(NotFound());
                }

                return(Ok(q));
            }
            catch (Exception e)
            {
                // TODO: Log exception
                _logger.LogError("API_ERR | GET_EMPLOYEE | ID: {0} | ERR: {1}", id.ToString(), e.Message.ToString());
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
예제 #19
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var value = (long)reader.Value;

            return(DateTimeExtensions.ToDateTime(value));
        }
예제 #20
0
 public void FirstWorkDays()
 {
     var d = DateTimeExtensions.FirstWorkDays(2019, 8, 6);
 }
예제 #21
0
        /// <summary>
        /// Sets the index curve range.
        /// </summary>
        /// <param name="log">The log.</param>
        /// <param name="ranges">The ranges.</param>
        /// <param name="indexCurve">The index curve.</param>
        /// <param name="isTimeLog">if set to <c>true</c> [is time log].</param>
        private void SetIndexCurveRange(Log log, Dictionary <string, Range <double?> > ranges, string indexCurve, bool isTimeLog)
        {
            if (!ranges.ContainsKey(indexCurve))
            {
                return;
            }

            var range = ranges[indexCurve];

            Logger.DebugFormat("Setting log index curve ranges: {0}; {1}", indexCurve, range);

            if (isTimeLog)
            {
                if (log.StartDateTimeIndex != null)
                {
                    if (range.Start.HasValue && !double.IsNaN(range.Start.Value))
                    {
                        log.StartDateTimeIndex = DateTimeExtensions.FromUnixTimeMicroseconds((long)range.Start.Value);
                    }
                    else
                    {
                        log.StartDateTimeIndex = null;
                    }
                }

                if (log.EndDateTimeIndex != null)
                {
                    if (range.End.HasValue && !double.IsNaN(range.End.Value))
                    {
                        log.EndDateTimeIndex = DateTimeExtensions.FromUnixTimeMicroseconds((long)range.End.Value);
                    }
                    else
                    {
                        log.EndDateTimeIndex = null;
                    }
                }
            }
            else
            {
                if (log.StartIndex != null)
                {
                    if (range.Start.HasValue)
                    {
                        log.StartIndex.Value = range.Start.Value;
                    }
                    else
                    {
                        log.StartIndex = null;
                    }
                }

                if (log.EndIndex != null)
                {
                    if (range.End.HasValue)
                    {
                        log.EndIndex.Value = range.End.Value;
                    }
                    else
                    {
                        log.EndIndex = null;
                    }
                }
            }
        }
예제 #22
0
        public static void RemovePlayerFromGame(Net.GS.GameClient gameClient)
        {
            if (gameClient == null || gameClient.Game == null)
            {
                return;
            }

            var gameId = gameClient.Game.GameId;

            if (!Games.ContainsKey(gameId))
            {
                return;
            }

            var game = Games[gameId];

            if (!game.Players.ContainsKey(gameClient))
            {
                return;
            }

            Player p = null;

            if (!game.Players.TryRemove(gameClient, out p))
            {
                Logger.Error("Can't remove player ({0}) from game with id: {1}", gameClient.Player.Toon.Name, gameId);
            }

            if (p != null)
            {
                //TODO: Move this inside player OnLeave event
                var toon        = p.Toon;
                var gameAccount = toon.DBToon.DBGameAccount; // For update account profile [Necrosummon]
                toon.TimePlayed    += DateTimeExtensions.ToUnixTime(DateTime.UtcNow) - toon.LoginTime;
                toon.ExperienceNext = p.Attributes[GameAttribute.Experience_Next];

                if (toon.Class == ToonClass.Barbarian)
                {
                    gameAccount.BarbarianPlayedTime += DateTimeExtensions.ToUnixTime(DateTime.UtcNow) - toon.LoginTime;

                    if (gameAccount.BarbarianHighestLevel < toon.Level) // Updates the Highest Level of this class if is more high when you logout [Necrosummon]
                    {
                        gameAccount.BarbarianHighestLevel = toon.Level;
                    }
                }
                else if (toon.Class == ToonClass.DemonHunter)
                {
                    gameAccount.DemonHunterPlayedTime += DateTimeExtensions.ToUnixTime(DateTime.UtcNow) - toon.LoginTime;

                    if (gameAccount.DemonHunterHighestLevel < toon.Level)
                    {
                        gameAccount.DemonHunterHighestLevel = toon.Level;
                    }
                }
                else if (toon.Class == ToonClass.Monk)
                {
                    gameAccount.MonkPlayedTime += DateTimeExtensions.ToUnixTime(DateTime.UtcNow) - toon.LoginTime;

                    if (gameAccount.MonkHighestLevel < toon.Level)
                    {
                        gameAccount.MonkHighestLevel = toon.Level;
                    }
                }
                else if (toon.Class == ToonClass.WitchDoctor)
                {
                    gameAccount.WitchDoctorPlayedTime += DateTimeExtensions.ToUnixTime(DateTime.UtcNow) - toon.LoginTime;

                    if (gameAccount.WitchDoctorHighestLevel < toon.Level)
                    {
                        gameAccount.WitchDoctorHighestLevel = toon.Level;
                    }
                }
                else if (toon.Class == ToonClass.Wizard)
                {
                    gameAccount.WizardPlayedTime += DateTimeExtensions.ToUnixTime(DateTime.UtcNow) - toon.LoginTime;

                    if (gameAccount.WizardHighestLevel < toon.Level)
                    {
                        gameAccount.WizardHighestLevel = toon.Level;
                    }
                }

                // Hardcore Highest Level Account Profile Info
                if (toon.Hardcore && gameAccount.HighestHardcoreLevel < toon.Level)
                {
                    gameAccount.HighestHardcoreLevel = toon.Level;
                }

                // Remove Player From World
                if (p.InGameClient != null)
                {
                    p.World.Leave(p);
                }
                // Generate Update for Client
                gameClient.BnetClient.Account.CurrentGameAccount.NotifyUpdate();
                //save hero to db after player data was updated in toon
                ToonManager.SaveToDB(toon);
            }

            if (game.Players.Count == 0)
            {
                Games.Remove(gameId); // we should be also disposing it /raist.
            }
        }
예제 #23
0
 public DateTime ToDateTime(TimeSpan a) => DateTimeExtensions.DateTime1970() + a;
예제 #24
0
 public string getDatePublished()
 {
     return(DateTimeExtensions.DateTimeToString(datePublished));
 }
예제 #25
0
        public static VkPhoto FromJson(JToken json)
        {
            if (json == null)
            {
                throw new ArgumentNullException("json");
            }

            var result = new VkPhoto();

            if (json["id"] != null)
            {
                result.Id = (long)json["id"];
            }

            if (json["album_id"] != null)
            {
                result.AlbumId = (long)json["album_id"];
            }

            if (json["owner_id"] != null)
            {
                result.OwnerId = (long)json["owner_id"];
            }

            if (json["photo_75"] != null)
            {
                result.Photo75 = (string)json["photo_75"];
            }

            if (json["photo_130"] != null)
            {
                result.Photo130 = (string)json["photo_130"];
            }

            if (json["photo_604"] != null)
            {
                result.Photo604 = (string)json["photo_604"];
            }

            if (json["photo_807"] != null)
            {
                result.Photo807 = (string)json["photo_807"];
            }

            if (json["photo_1280"] != null)
            {
                result.Photo1280 = (string)json["photo_1280"];
            }

            if (json["photo_2560"] != null)
            {
                result.Photo2560 = (string)json["photo_2560"];
            }

            if (json["width"] != null)
            {
                result.Width = (int)json["width"];
            }

            if (json["height"] != null)
            {
                result.Height = (int)json["height"];
            }

            if (json["text"] != null)
            {
                result.Text = (string)json["text"];
            }

            if (json["date"] != null)
            {
                result.Created = DateTimeExtensions.UnixTimeStampToDateTime((long)json["date"]);
            }

            return(result);
        }
예제 #26
0
 public string getDatePublishEndRepresentation()
 {
     return(DateTimeExtensions.DateTimeToString(datePublishEnd));
 }
예제 #27
0
        static void TestDate(DateTime date)
        {
            warpup--;

            // NOTE: benchmark meaningless, first algorithm will have x3 time
            if (warpup < 0)
            {
                sw1.Start();
            }
            var jd1 = ComputeJulianDayNREL(date); // has strange condition for gregorian date < year 1582

            if (warpup < 0)
            {
                sw1.Stop();
            }

            if (warpup < 0)
            {
                sw2.Start();
            }
            var jd2 = ComputeJulianDayInt2(date);

            if (warpup < 0)
            {
                sw2.Stop();
            }

            if (warpup < 0)
            {
                sw3.Start();
            }
            var jd3 = ComputeJulianDayMeeus(date);

            if (warpup < 0)
            {
                sw3.Stop();
            }

            if (warpup < 0)
            {
                sw4.Start();
            }
            var jd4 = ComputeJulianDayInt(date);

            if (warpup < 0)
            {
                sw4.Stop();
            }

            // NOTE: there would be any internal void GetDatePart(out int year, out int month, out int day) hidden in the .net framework
            if (warpup < 0)
            {
                sw0.Start();
            }
            var year  = date.Year;
            var month = date.Month;
            var day   = date.Day;

            if (warpup < 0)
            {
                sw0.Stop();
            }

            if (warpup < 0)
            {
                sw5.Start();
            }
            var jd5 = (double)ComputeJulianDay(year, month, day);

            if (warpup < 0)
            {
                sw5.Stop();
            }

            jd5 += date.TimeOfDay.TotalDays - 0.5;

            var jdAard = date.ComputeJulianDay();

            //Report.Line("Date={0} Julian Day NREL: {1} ALT:{2}", date, (int)jd1, (int)jd2);

            if (!jd1.ApproximateEquals(jd2, 1e-07) || !jd1.ApproximateEquals(jd3, 1e-07) || !jd1.ApproximateEquals(jd4, 1e-07) || !jd1.ApproximateEquals(jdAard, 1e-7))
            {
                Report.Line("Date={0} Julian Day NREL: {1} ALT:{2}", date, (int)jd1, (int)jd2);
                Report.Line("FAIL");
            }

            var gd  = ComputeGregorianDay(date);
            var gd1 = date.Day + date.TimeOfDay.TotalDays;

            var gdAard = DateTimeExtensions.GregorianDayOfMonthFromJulianDay(jd1);

            if (!gd.ApproximateEquals(gd1, 1e-5) || !gd.ApproximateEquals(gdAard, 1e-5))
            {
                Report.Line("Date={0} Julian Day: {1} Gregorian Day: {2} {3} {4}", date, jd1, gd, gd1, gdAard);
                Report.Line("FAIL");
            }


            var date2 = DateTimeExtensions.ComputeDateFromJulianDay(jd1);
            var dt    = date - date2;

            if ((int)dt.TotalSeconds != 0)
            {
                Report.Line("DateIn={0} Julian Day={1} DateOut={2}", date, jd1, date2);
                Report.Line("FAIL");
            }

            if (year > 1)
            {
                var date3 = DateTimeExtensions.ComputeDateFromJulianDay((int)jd1);
                var tmp   = new DateTime(year, month, day, 12, 0, 0); // 12h noon
                if (jd1.Frac() > 0.5)
                {
                    tmp = tmp.AddDays(-1);
                }
                var dt2 = tmp - date3;
                if ((int)dt2.TotalSeconds != 0)
                {
                    Report.Line("DateIn={0} Julian Day={1} DateOut={2}", tmp, jd1, date3);
                    Report.Line("FAIL");
                }
            }
        }
예제 #28
0
        public void The_default_time_out_should_be_1_day()
        {
            TransportMessageHeaderHelper.SetHeader(_message, SecondLevelRetriesHeaders.RetriesTimestamp, DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow.AddDays(-1).AddSeconds(-1)));

            var retriesProcessor = new SecondLevelRetriesProcessor
            {
                SecondLevelRetriesConfiguration = new SecondLevelRetriesConfiguration()
            };

            var hasTimedOut = retriesProcessor.SecondLevelRetriesConfiguration.RetryPolicy(_message) == TimeSpan.MinValue;

            Assert.IsTrue(hasTimedOut);
        }
예제 #29
0
        //TODO Readable
        //TODO Title_version
        //TODO Explicit


        public static ITrack FromJson(JToken json, IDeezerClient client)
        {
            var      releaseDateString = json.Value <string>(RELEASE_PROPERTY_NAME);
            DateTime?releaseDate       = DateTimeExtensions.ParseApiDateTime(releaseDateString);

            //TODO -> AvailableFrom property??
            //var availabilityDateString = json.Value<String>(TimeAdd)

            /* Tracks don't always come with their own artwork.
             * Instead, we'll pinch the artwork from the 'Album' property
             * if this is available in the returned JSON. */
            var containedInAlbum = Api.Album.FromJson(json[ALBUM_PROPERTY_NAME], client);

            var internalArtwork = Api.Images.FromJson(json);

            var actualArtwork = new TrackImages(containedInAlbum,
                                                internalArtwork?.Small,
                                                internalArtwork?.Medium,
                                                internalArtwork?.Large,
                                                internalArtwork?.ExtraLarge);

            bool hasAvailabiltyList = (json as JObject)?.ContainsKey(AVAILABLE_COUNTRY_PROPERTY_NAME) ?? false;

            // Json.Values<string>() is lazy, need to wrap and eval into a list at this point
            // as the underlying json is disposed as soon as the parsing has been completed.
            IEnumerable <string> availableInList = hasAvailabiltyList ? new List <string>(json[AVAILABLE_COUNTRY_PROPERTY_NAME].Values <string>())
                                                                     : new List <string>(0);

            return(new Track()
            {
                Id = json.Value <ulong>(ID_PROPERTY_NAME),

                Title = json.Value <string>(TITLE_PROPERTY_NAME),
                ShortTitle = json.Value <string>(SHORT_TITLE_PROPERTY_NAME),

                ISRC = json.Value <string>(ISRC_PROPERTY_NAME),
                Link = json.Value <string>(LINK_PROPERTY_NAME),
                ShareLink = json.Value <string>(SHARE_LINK_PROPERTY_NAME),
                PreviewLink = json.Value <string>(PREVIEW_PROPERTY_NAME),

                Duration = json.Value <uint>(DURATION_PROPERTY_NAME),
                BPM = json.Value <float>(BPM_PROPERTY_NAME),
                Gain = json.Value <float>(GAIN_PROPERTY_NAME),

                TrackNumber = json.Value <uint>(TRACK_NUMBER_PROPERTY_NAME),
                DiscNumber = json.Value <uint>(DISC_NUMBER_PROPERTY_NAME),

                Rank = json.Value <uint>(RANK_PROPERTY_NAME),

                ReleaseDate = releaseDate,

                Artwork = actualArtwork,

                AvailableIn = availableInList,

                Artist = Api.Artist.FromJson(json[ARTIST_PROPERTY_NAME], client),
                Album = containedInAlbum,
                Contributors = CollectionOf <IArtist> .FromJson(json[CONTRIBUTORS_PROPERTY_NAME], x => Api.Artist.FromJson(x, client)),

                // ISssionObject
                Client = client,
            });
        }
예제 #30
0
        public void GetBeijingTime()
        {
            var ts = DateTimeExtensions.UtcMillisecondsToBeiJingTime(LongTimestamp);

            Assert.Equal(Time.AddHours(8D), ts);
        }