Inheritance: System.Web.UI.Page
        public void submitTime(TimeEvent te)
        {
            _timeevents.Add(te);
            /*if(te.Issue.SpentHours != null)
            {
                te.Issue.SpentHours = te.Issue.SpentHours + (float)Math.Round((decimal)te.Timespan.TotalHours, 2);
            } else
            {
                te.Issue.SpentHours = (float)Math.Round((float)te.Timespan.TotalHours, 2);
            } */
            TimeEntry timeentry = new TimeEntry();
            timeentry.Hours = Math.Round((decimal)te.Timespan.TotalHours, 2);
            timeentry.Project = new IdentifiableName { Id = te.Issue.Project.Id };
            timeentry.Activity = new IdentifiableName { Id = te.Activity };
            timeentry.Comments = te.Comment;
            timeentry.Issue = new IdentifiableName {Id = te.Issue.Id };

            //manager.
            try
            {
                manager.CreateObject(timeentry);
            //manager.UpdateObject(timeentry.Id.ToString(), (TimeEntry)timeentry);
            } catch (RedmineException e)
            {
                Console.WriteLine(e.Message);
            }
        }
 DateTime GetCompatibleDate(TimeEntry timeEntry)
 {
     var date = new DateTime(timeEntry.TimeRecorded.Year,
         timeEntry.TimeRecorded.Month,
         timeEntry.TimeRecorded.Day, 0, 0, 0, DateTimeKind.Utc);
     return date;
 }
        public TimeEntry GetLastTimeEntry(bool getInternal = false)
        {
            using (var cnn = GetConnection())
            using (var cmd = cnn.CreateCommand())
            {
                var internalWhere = (getInternal) ? "" : "WHERE Internal = 0";

                cmd.CommandText = "SELECT * FROM TimeEntries "+internalWhere+" ORDER BY Id DESC LIMIT 1";

                using (var reader = cmd.ExecuteReader())
                {
                    if (!reader.Read()) return null;

                    var timeEntry = new TimeEntry
                    {
                        TimeRecorded =
                            DateTime.SpecifyKind(reader.GetDateTime(reader.GetOrdinal("TimeRecorded")),
                                DateTimeKind.Local),
                        Comment = reader.Get<string>("Comment"),
                        Id = reader.Get<int>("Id"),
                        Task = _localTaskRepository.GetTaskById(reader.Get<string>("TaskId")),
                        AssociatedTask = _localTaskRepository.GetTaskById(reader.Get<string>("AssociatedTaskId")),
                        Synced = reader.Get<bool>("Synced"),
                        MinutesSpent = reader.Get<int>("MinutesSpent"),
                        Internal = reader.Get<bool>("Internal"),
                        Project = _localProjectRepository.GetProjectById(reader.Get<string>("ProjectId"))
                    };

                    return timeEntry;
                }
            }
        }
        bool RecordTime(TimeEntry timeEntry, Task task)
        {
            var timeEntryModel = new TimeEntryModel
            {
                Date = GetCompatibleDate(timeEntry).ToString("O"),
                Notes = timeEntry.Comment,
                TimeString = timeEntry.MinutesSpent + "m",
                DurationSeconds = timeEntry.MinutesSpent*60,
                ProjectId = timeEntry.Project?.Id,
                TaskId = task?.Id,
                WorkItems = new List<string>(), // TODO: add functionality for tracking WorkItems
            };

            var post = new RestRequest
            {
                Resource = "Time/Save",
                Method = Method.POST,
                RequestFormat = DataFormat.Json
            };

            post.AddBody(timeEntryModel);

            var result = _api.Execute<TimeEntryModel>(post);
            return result != null;
        }
        /// <summary>
        ///     When overridden in a derived class, converts the provided dictionary into an object of the specified type.
        /// </summary>
        /// <param name="dictionary">
        ///     An <see cref="T:System.Collections.Generic.IDictionary`2" /> instance of property data stored
        ///     as name/value pairs.
        /// </param>
        /// <param name="type">The type of the resulting object.</param>
        /// <param name="serializer">The <see cref="T:System.Web.Script.Serialization.JavaScriptSerializer" /> instance.</param>
        /// <returns>
        ///     The deserialized object.
        /// </returns>
        public override object Deserialize(IDictionary<string, object> dictionary, Type type,
            JavaScriptSerializer serializer)
        {
            if (dictionary != null)
            {
                var timeEntry = new TimeEntry();

                timeEntry.Id = dictionary.GetValue<int>(RedmineKeys.ID);
                timeEntry.Activity =
                    dictionary.GetValueAsIdentifiableName(dictionary.ContainsKey(RedmineKeys.ACTIVITY)
                        ? RedmineKeys.ACTIVITY
                        : RedmineKeys.ACTIVITY_ID);
                timeEntry.Comments = dictionary.GetValue<string>(RedmineKeys.COMMENTS);
                timeEntry.Hours = dictionary.GetValue<decimal>(RedmineKeys.HOURS);
                timeEntry.Issue =
                    dictionary.GetValueAsIdentifiableName(dictionary.ContainsKey(RedmineKeys.ISSUE)
                        ? RedmineKeys.ISSUE
                        : RedmineKeys.ISSUE_ID);
                timeEntry.Project =
                    dictionary.GetValueAsIdentifiableName(dictionary.ContainsKey(RedmineKeys.PROJECT)
                        ? RedmineKeys.PROJECT
                        : RedmineKeys.PROJECT_ID);
                timeEntry.SpentOn = dictionary.GetValue<DateTime?>(RedmineKeys.SPENT_ON);
                timeEntry.User = dictionary.GetValueAsIdentifiableName(RedmineKeys.USER);
                timeEntry.CustomFields = dictionary.GetValueAsCollection<IssueCustomField>(RedmineKeys.CUSTOM_FIELDS);
                timeEntry.CreatedOn = dictionary.GetValue<DateTime?>(RedmineKeys.CREATED_ON);
                timeEntry.UpdatedOn = dictionary.GetValue<DateTime?>(RedmineKeys.UPDATED_ON);

                return timeEntry;
            }

            return null;
        }
        public void Should_Create_Time_Entry()
        {
            TimeEntry timeEntry = new TimeEntry();
            timeEntry.Issue = new IdentifiableName { Id = NEW_TIME_ENTRY_ISSUE_ID };
            timeEntry.Project = new IdentifiableName { Id = NEW_TIME_ENTRY_PROJECT_ID };
            timeEntry.SpentOn = NEW_TIME_ENTRY_DATE;
            timeEntry.Hours = NEW_TIME_ENTRY_HOURS;
            timeEntry.Activity = new IdentifiableName { Id = NEW_TIME_ENTRY_ACTIVITY_ID };
            timeEntry.Comments = NEW_TIME_ENTRY_COMMENTS;

            TimeEntry savedTimeEntry = redmineManager.CreateObject<TimeEntry>(timeEntry);

            Assert.IsNotNull(savedTimeEntry, "Create time entry returned null.");
            Assert.IsNotNull(savedTimeEntry.Issue, "Saved time entry issue is null.");
            Assert.AreEqual(savedTimeEntry.Issue.Id, NEW_TIME_ENTRY_ISSUE_ID, "Issue id is invalid.");
            Assert.IsNotNull(savedTimeEntry.Project, "Saved time entry project is null.");
            Assert.AreEqual(savedTimeEntry.Project.Id, NEW_TIME_ENTRY_PROJECT_ID, "Project id is invalid.");
            Assert.IsNotNull(savedTimeEntry.SpentOn, "Saved time entry date is null.");
            Assert.AreEqual(savedTimeEntry.SpentOn.Value.Date, NEW_TIME_ENTRY_DATE.Date, "Date is invalid.");
            Assert.IsNotNull(savedTimeEntry.Hours, "Saved time entry hours is null.");
            Assert.AreEqual(savedTimeEntry.Hours, NEW_TIME_ENTRY_HOURS, "Hours value is not valid.");
            Assert.IsNotNull(savedTimeEntry.Activity, "Saved time entry activity is null.");
            Assert.AreEqual(savedTimeEntry.Activity.Id, NEW_TIME_ENTRY_ACTIVITY_ID, "Activity id is invalid.");
            Assert.IsNotNull(savedTimeEntry.Comments, "Saved time entry comment is null.");
            Assert.AreEqual(savedTimeEntry.Comments, NEW_TIME_ENTRY_COMMENTS, "Coments value is invalid.");
        }
        /// <summary>
        /// https://www.toggl.com/public/api#post_time_entries
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public TimeEntry Add(TimeEntry obj)
        {
            var url = ApiRoutes.TimeEntry.TimeEntriesUrl;

            var timeEntry = ToggleSrv.Post(url, obj.ToJson()).GetData<TimeEntry>();

            return timeEntry;
        }
        /// <summary>
        /// https://www.toggl.com/public/api#put_time_entries
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public TimeEntry Edit(TimeEntry obj)
        {
            var url = string.Format(ApiRoutes.TimeEntry.TimeEntryUrl, obj.Id);

            var timeEntry = ToggleSrv.Put(url, obj.ToJson()).GetData<TimeEntry>();

            return timeEntry;
        }
示例#9
0
        public void GetDetailedReportSince()
        {
            var timeEntryService = new TimeEntryService(Constants.ApiToken);
            for (int i = 0; i < 6; i++)
            {
                var timeEntry = new TimeEntry()
                {
                    IsBillable = true,
                    CreatedWith = "TimeEntryTestAdd",
                    Description = "Test Desc" + DateTime.Now.Ticks,
                    Duration = 900,
                    Start = DateTime.Now.AddDays(-i).ToIsoDateStr(),
                    Stop = DateTime.Now.AddDays(-i).AddMinutes(20).ToIsoDateStr(),
                    ProjectId = DefaultProjectId,
                    WorkspaceId = DefaultWorkspaceId
                };
                var expTimeEntry = timeEntryService.Add(timeEntry);
                Assert.IsNotNull(expTimeEntry);
            }

			var standardParams = new DetailedReportParams()
			{
				UserAgent = "TogglAPI.Net",
				WorkspaceId = DefaultWorkspaceId				
			};

            var result = ReportService.Detailed(standardParams);
            Assert.AreEqual(result.Data.Count, 6);
            Assert.AreEqual(result.TotalCount, 6);

            var te = new TimeEntry()
            {
                IsBillable = true,
                CreatedWith = "TimeEntryTestAdd",
                Description = "Test Desc" + DateTime.Now.Ticks,
                Duration = 900,
                Start = DateTime.Now.AddDays(-7).ToIsoDateStr(),
                Stop = DateTime.Now.AddDays(-7).AddMinutes(20).ToIsoDateStr(),
                ProjectId = DefaultProjectId,
                WorkspaceId = DefaultWorkspaceId
            };
            var expTe = timeEntryService.Add(te);
            Assert.IsNotNull(expTe);

            result = ReportService.Detailed(standardParams);
            Assert.AreEqual(result.Data.Count, 6);
            Assert.AreEqual(result.TotalCount, 6);

            result = ReportService.Detailed(new DetailedReportParams()
                                            {
                                                UserAgent = "test_api",
                                                WorkspaceId = DefaultWorkspaceId,
                                                Since = DateTime.Now.AddDays(-7).ToIsoDateStr()
                                            });
            Assert.AreEqual(result.Data.Count, 7);
            Assert.AreEqual(result.TotalCount, 7);
        }
示例#10
0
    protected void AddEntry_Click(object sender, System.EventArgs e)
    {
        TimeEntry timeEntry = new TimeEntry(Page.User.Identity.Name, Convert.ToInt32(CategoryList.SelectedValue), Convert.ToDecimal(Hours.Text), DateTime.Now, UserList.SelectedValue);
        timeEntry.Description = Description.Text;
        timeEntry.Save();

        Description.Text = string.Empty;
        Hours.Text = string.Empty;
        ProjectListGridView.DataBind();
    }
示例#11
0
        private void ok_Click(object sender, EventArgs e)
        {
            TimeEntry timeEntry = new TimeEntry();
            timeEntry.ProjectName = projectName.Text;
            WorkTajmViewModel.Instance.TimeEntries.Add(timeEntry);

            if (this.NavigationService.CanGoBack)
            {
                this.NavigationService.GoBack();
            }
        }
示例#12
0
        public void ShouldHaveStartTimeProperty()
        {
            // Arrange
            var sut = new TimeEntry();
            var expected = "StartTime";
            // Act
            var result = sut.GetType().GetProperty(expected);

            // Assert
            Assert.NotNull(result);
        }
 public TimeEntryForm(Issue issue, IList<ProjectMember> projectMembers)
 {
     InitializeComponent();
     this.issue = issue;
     this.projectMembers = projectMembers;
     type = eFormType.New;
     CurTimeEntry = new TimeEntry();
     LoadLanguage();
     LoadCombos();
     comboBoxByUser.SelectedValue = RedmineClientForm.Instance.CurrentUser.Id;
 }
示例#14
0
        public MiteRunnerResult SaveTimeEntry(TimeEntry time)
        {
            if (time == null)
                throw new ArgumentNullException("time");

            var result = new MiteRunnerResult();

            //set default values
            var project = string.IsNullOrWhiteSpace(time.Project) ? _configuration.DefaultProject : time.Project;
            var customer = string.IsNullOrWhiteSpace(time.Customer) ? _configuration.DefaultCustomer : time.Customer;
            var service = string.IsNullOrWhiteSpace(time.Service) ? _configuration.DefaultService : time.Service;

            //find the matching project
            if (string.IsNullOrWhiteSpace(project))
                throw new ArgumentException("No project specified.");
            if (string.IsNullOrWhiteSpace(customer))
                throw new ArgumentException("No customer specified.");

            var allProjects = _mite.GetAll<Project>().ToList();
            var allServices = _mite.GetAll<Service>().ToList();

            var foundProject =
                allProjects.FirstOrDefault(
                    x =>
                    x.Name.Equals(project, StringComparison.InvariantCultureIgnoreCase) &&
                    x.Customer.Name.Equals(customer, StringComparison.InvariantCultureIgnoreCase));
            if (foundProject == null)
                throw new ApplicationException("Project '" + project + "' for customer '" + customer + "' not found.");

            //find the matching service, if any
            Service foundService = null;
            if (!string.IsNullOrWhiteSpace(service))
                foundService = allServices.FirstOrDefault(x => x.Name.Equals(service, StringComparison.InvariantCultureIgnoreCase));

            //add the time-entry to mite
            _mite.Create(new Mite.TimeEntry
                {
                    Date = time.Date,
                    Service = foundService,
                    Minutes = time.Minutes,
                    Project = foundProject,
                    Note = time.Notes
                });

            result.Customer = customer;
            result.Project = foundProject.Name;
            result.Service = foundService == null ? "" : foundService.Name;

            return result;
        }
示例#15
0
        public void RedmineTimeEntries_ShouldAdd()
        {
            TimeEntry timeEntry = new TimeEntry();
            timeEntry.Issue = new IdentifiableName { Id = 19 };
            timeEntry.Project = new IdentifiableName { Id = 10 };
            timeEntry.SpentOn = DateTime.Now;
            timeEntry.Hours = 1;
            timeEntry.Activity = new IdentifiableName { Id = 16 };
            timeEntry.Comments = "Added time entry on project";

            TimeEntry savedTimeEntry = redmineManager.CreateObject<TimeEntry>(timeEntry);

            Assert.AreEqual(timeEntry.Comments, savedTimeEntry.Comments);
        }
示例#16
0
        public void ToString_25h48m7s180f()
        {
            var ts = new TimeSpan(1, 01, 48, 07, 180);
            var entry = new TimeEntry(1, ts);
            var precision = 3;
            var culture = CultureInfo.InvariantCulture;

            var s = entry.ToString(TimeEntry.Display.Seconds, precision, culture);
            var m = entry.ToString(TimeEntry.Display.Minutes, precision -1, culture);
            var h = entry.ToString(TimeEntry.Display.Hours, precision, culture);
            var d = entry.ToString(TimeEntry.Display.Days, precision, culture);

            Assert.AreEqual("001     92,887.180", s, "Seconds");
            Assert.AreEqual("001   1,548:07.18", m, "Minutes");
            Assert.AreEqual("001   25:48:07.180", h, "Hours");
            Assert.AreEqual("001 1:01:48:07.180", d, "Days");
        }
        public TimeEntryForm(Issue issue, IList<ProjectMember> projectMembers, TimeEntry timeEntry)
        {
            InitializeComponent();
            this.issue = issue;
            this.projectMembers = projectMembers;
            type = eFormType.Edit;
            CurTimeEntry = timeEntry;
            LoadLanguage();
            LoadCombos();

            if (CurTimeEntry.SpentOn.HasValue)
                datePickerSpentOn.Value = CurTimeEntry.SpentOn.Value;

            comboBoxByUser.SelectedValue = CurTimeEntry.User.Id;
            comboBoxActivity.SelectedValue = CurTimeEntry.Activity.Id;
            textBoxSpentHours.Text = CurTimeEntry.Hours.ToString();
            textBoxComment.Text = CurTimeEntry.Comments;
        }
示例#18
0
        public void Update(int Id, int Timesheetid, int Day, string Timein, string Timeout, string Notes)
        {
            TimeEntry item = new TimeEntry();
            item.MarkOld();
            item.IsLoaded = true;

            item.Id = Id;
            item.Timesheetid = Timesheetid;
            item.Day = Day;
            item.Timein = Timein;
            item.Timeout = Timeout;
            item.Notes = Notes;
            item.IsDeleted = false;
            item.CreatedOn = null;
            item.CreatedBy = null;
            item.ModifiedOn = null;
            item.ModifiedBy = null;
            
            item.Save(UserName);
        }
        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary != null)
            {
                var timeEntry = new TimeEntry();

                timeEntry.Id = dictionary.GetValue<int>("id");
                timeEntry.Activity = dictionary.GetValueAsIdentifiableName(dictionary.ContainsKey("activity") ? "activity" : "activity_id");
                timeEntry.Comments = dictionary.GetValue<string>("comments");
                timeEntry.Hours = dictionary.GetValue<decimal>("hours");
                timeEntry.Issue = dictionary.GetValueAsIdentifiableName(dictionary.ContainsKey("issue") ? "issue" : "issue_id");
                timeEntry.Project = dictionary.GetValueAsIdentifiableName(dictionary.ContainsKey("project") ? "project" : "project_id");
                timeEntry.SpentOn = dictionary.GetValue<DateTime?>("spent_on");
                timeEntry.User = dictionary.GetValueAsIdentifiableName("user");
                timeEntry.CustomFields = dictionary.GetValueAsCollection<IssueCustomField>("custom_fields");
                timeEntry.CreatedOn = dictionary.GetValue<DateTime?>("created_on");
                timeEntry.UpdatedOn = dictionary.GetValue<DateTime?>("updated_on");

                return timeEntry;
            }

            return null;
        }
示例#20
0
    protected void AddEntry_Click(object sender, System.EventArgs e)
    {
        Page.Validate();
        if (Page.IsValid == false)
        return;
        if (txtDate.Text != "" && txtDate.Text != null && Hours.Text != "" && Hours.Text != null && Hours.Text != "0.0" && Hours.Text != "0")
        {
        TimeEntry timeEntry = new TimeEntry(Page.User.Identity.Name, Convert.ToInt32(ProjectList.SelectedValue), Convert.ToInt32(CategoryList.SelectedValue), Convert.ToDecimal(Hours.Text), Convert.ToDateTime(txtDate.Text), Page.User.Identity.Name);
        timeEntry.Description = Description.Text;
        timeEntry.Save();
        }
        txtDate.Text = string.Empty;
        Description.Text = string.Empty;

        if (Convert.ToDecimal(Hours.Text) <= 0)
        {
        hourscheck.Visible = true;
        hourscheck.Text = "Hours should be greater than zero";
        }
        //hourscheck.Visible = false;
        Hours.Text = string.Empty;
        ProjectListGridView.DataBind();
    }
        public void Add()
        {
            var tags = new List<string>();
            tags.Add("one");

            var act = new TimeEntry()
                          {
                              IsBillable = true,
                              CreatedWith = "TimeEntryTestAdd",
                              Description = "Test Desc" + DateTime.Now.Ticks,
                              Duration = 900,
                              Start = DateTime.Now.ToIsoDateStr(),
                              Stop = DateTime.Now.AddMinutes(20).ToIsoDateStr(),
                              ProjectId =Constants.DefaultProjectId,
                              TagNames = tags,
                              WorkspaceId = Constants.DefaultWorkspaceId

            };

            var exp = timeEntrySrv.Add(act);

            Assert.GreaterOrEqual(exp.Id, 0);
        }
示例#22
0
        public void Should_Create_Time_Entry()
        {
            const int NEW_TIME_ENTRY_ISSUE_ID = 18;
            const int NEW_TIME_ENTRY_PROJECT_ID = 9;
            DateTime NEW_TIME_ENTRY_DATE = DateTime.Now;
            const int NEW_TIME_ENTRY_HOURS = 1;
            const int NEW_TIME_ENTRY_ACTIVITY_ID = 16;
            const string NEW_TIME_ENTRY_COMMENTS = "Added time entry on project";

            var timeEntry = new TimeEntry
            {
                Issue = new IdentifiableName {Id = NEW_TIME_ENTRY_ISSUE_ID},
                Project = new IdentifiableName {Id = NEW_TIME_ENTRY_PROJECT_ID},
                SpentOn = NEW_TIME_ENTRY_DATE,
                Hours = NEW_TIME_ENTRY_HOURS,
                Activity = new IdentifiableName {Id = NEW_TIME_ENTRY_ACTIVITY_ID},
                Comments = NEW_TIME_ENTRY_COMMENTS
            };

            var savedTimeEntry = fixture.RedmineManager.CreateObject(timeEntry);

            Assert.NotNull(savedTimeEntry);
            Assert.NotNull(savedTimeEntry.Issue);
            Assert.True(savedTimeEntry.Issue.Id == NEW_TIME_ENTRY_ISSUE_ID, "Issue id is invalid.");
            Assert.NotNull(savedTimeEntry.Project);
            Assert.True(savedTimeEntry.Project.Id == NEW_TIME_ENTRY_PROJECT_ID, "Project id is invalid.");
            Assert.NotNull(savedTimeEntry.SpentOn);
            Assert.True(DateTime.Compare(savedTimeEntry.SpentOn.Value.Date, NEW_TIME_ENTRY_DATE.Date) == 0,
                "Date is invalid.");
            Assert.NotNull(savedTimeEntry.Hours);
            Assert.True(savedTimeEntry.Hours == NEW_TIME_ENTRY_HOURS, "Hours value is not valid.");
            Assert.NotNull(savedTimeEntry.Activity);
            Assert.True(savedTimeEntry.Activity.Id == NEW_TIME_ENTRY_ACTIVITY_ID, "Activity id is invalid.");
            Assert.NotNull(savedTimeEntry.Comments);
            Assert.True(savedTimeEntry.Comments.Equals(NEW_TIME_ENTRY_COMMENTS), "Coments value is invalid.");
        }
示例#23
0
        public void InitTest()
        {
            var timeEntry = new TimeEntry();

            Assert.AreEqual(timeEntry, TimeEntry.Zero);

            Assert.AreEqual(TimeEntry.Zero, new TimeEntry());
            Assert.AreEqual(TimeEntry.Zero, default(TimeEntry));

            Assert.Throws <ArgumentException>(() => new TimeEntry(0, 0, 10, 10));

            timeEntry = new TimeEntry(10, 20);
            Assert.AreEqual(10, timeEntry.Hours);
            Assert.AreEqual(20, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(0, timeEntry.Decimals);
            Assert.AreEqual(620, timeEntry.GetTotalMinutes());

            timeEntry = new TimeEntry(10, 80);
            Assert.AreEqual(11, timeEntry.Hours);
            Assert.AreEqual(20, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(0, timeEntry.Decimals);
            Assert.AreEqual(680, timeEntry.GetTotalMinutes());

            timeEntry = new TimeEntry(10, 60);
            Assert.AreEqual(11, timeEntry.Hours);
            Assert.AreEqual(0, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(0, timeEntry.Decimals);
            Assert.AreEqual(660, timeEntry.GetTotalMinutes());

            timeEntry = new TimeEntry(10, 59);
            Assert.AreEqual(10, timeEntry.Hours);
            Assert.AreEqual(59, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(0, timeEntry.Decimals);
            Assert.AreEqual(659, timeEntry.GetTotalMinutes());

            timeEntry = new TimeEntry(10, 61);
            Assert.AreEqual(11, timeEntry.Hours);
            Assert.AreEqual(1, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(0, timeEntry.Decimals);
            Assert.AreEqual(661, timeEntry.GetTotalMinutes());

            timeEntry = new TimeEntry(24, 0);
            Assert.AreEqual(24, timeEntry.Hours);
            Assert.AreEqual(0, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(0, timeEntry.Decimals);
            Assert.AreEqual(1440, timeEntry.GetTotalMinutes());

            timeEntry = new TimeEntry(24, 61);
            Assert.AreEqual(25, timeEntry.Hours);
            Assert.AreEqual(1, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(0, timeEntry.Decimals);
            Assert.AreEqual(1501, timeEntry.GetTotalMinutes());

            timeEntry = new TimeEntry(0, 1440);
            Assert.AreEqual(24, timeEntry.Hours);
            Assert.AreEqual(0, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(0, timeEntry.Decimals);
            Assert.AreEqual(1440, timeEntry.GetTotalMinutes());

            timeEntry = new TimeEntry(-10, -20);
            Assert.AreEqual(-10, timeEntry.Hours);
            Assert.AreEqual(-20, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(0, timeEntry.Decimals);
            Assert.AreEqual(-620, timeEntry.GetTotalMinutes());

            timeEntry = new TimeEntry(0, -5);
            Assert.AreEqual(0, timeEntry.Hours);
            Assert.AreEqual(-5, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(0, timeEntry.Decimals);
            Assert.AreEqual(-5, timeEntry.GetTotalMinutes());

            timeEntry = new TimeEntry(10, -5);
            Assert.AreEqual(9, timeEntry.Hours);
            Assert.AreEqual(55, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(0, timeEntry.Decimals);
            Assert.AreEqual(595, timeEntry.GetTotalMinutes());

            timeEntry = new TimeEntry(-10, -60);
            Assert.AreEqual(-11, timeEntry.Hours);
            Assert.AreEqual(0, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(0, timeEntry.Decimals);
            Assert.AreEqual(-660, timeEntry.GetTotalMinutes());

            timeEntry = new TimeEntry(-10, -80);
            Assert.AreEqual(-11, timeEntry.Hours);
            Assert.AreEqual(-20, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(0, timeEntry.Decimals);
            Assert.AreEqual(-680, timeEntry.GetTotalMinutes());

            timeEntry = new TimeEntry(-10, 60);
            Assert.AreEqual(-9, timeEntry.Hours);
            Assert.AreEqual(0, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(0, timeEntry.Decimals);
            Assert.AreEqual(-540, timeEntry.GetTotalMinutes());


            // Seconds
            timeEntry = new TimeEntry(10, 20, 13, 0);
            Assert.AreEqual(10, timeEntry.Hours);
            Assert.AreEqual(20, timeEntry.Minutes);
            Assert.AreEqual(13, timeEntry.Seconds);
            Assert.AreEqual(0, timeEntry.Decimals);
            Assert.AreEqual(620, timeEntry.GetTotalMinutes());

            timeEntry = new TimeEntry(10, 20, 63, 0);
            Assert.AreEqual(10, timeEntry.Hours);
            Assert.AreEqual(21, timeEntry.Minutes);
            Assert.AreEqual(3, timeEntry.Seconds);
            Assert.AreEqual(0, timeEntry.Decimals);
            Assert.AreEqual(621, timeEntry.GetTotalMinutes());

            timeEntry = new TimeEntry(10, 20, -83, 0);
            Assert.AreEqual(10, timeEntry.Hours);
            Assert.AreEqual(18, timeEntry.Minutes);
            Assert.AreEqual(37, timeEntry.Seconds);
            Assert.AreEqual(0, timeEntry.Decimals);
            Assert.AreEqual(618, timeEntry.GetTotalMinutes());

            // Decimals
            timeEntry = new TimeEntry(10, 20, 0, 10);
            Assert.AreEqual(10, timeEntry.Hours);
            Assert.AreEqual(20, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(10, timeEntry.Decimals);
            Assert.AreEqual(620, timeEntry.GetTotalMinutes());

            timeEntry = new TimeEntry(10, 20, 0, 123);
            Assert.AreEqual(10, timeEntry.Hours);
            Assert.AreEqual(21, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(23, timeEntry.Decimals);
            Assert.AreEqual(621, timeEntry.GetTotalMinutes());

            timeEntry = new TimeEntry(10, 20, 0, -345);
            Assert.AreEqual(10, timeEntry.Hours);
            Assert.AreEqual(16, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(55, timeEntry.Decimals);
            Assert.AreEqual(616, timeEntry.GetTotalMinutes());

            // Overflow
            timeEntry = new TimeEntry(10, -124, 0, -345);
            Assert.AreEqual(7, timeEntry.Hours);
            Assert.AreEqual(52, timeEntry.Minutes);
            Assert.AreEqual(0, timeEntry.Seconds);
            Assert.AreEqual(55, timeEntry.Decimals);
        }
示例#24
0
文件: DataAccess.cs 项目: slai/cwkb
        public Dictionary<int, List<TimeEntry>> GetTimeEntriesForTickets(int[] ticketIds)
        {
            var cmd = new SqlCommand();
            cmd.Connection = _conn;

            //http://stackoverflow.com/questions/337704/parameterizing-a-sql-in-clause/337792#337792
            var idsMap = new Dictionary<string, int>();
            for (var i = 0; i < ticketIds.Length; i++)
                idsMap["@id" + i.ToString()] = ticketIds[i];

            cmd.CommandText = @"SELECT Time_RecID, Member_ID, Notes, Date_Start, Time_Start, Time_End, Internal_Note,
                                       Hours_Actual, Hours_Bill, TE_Status.Description AS __Status, SR_Service_RecID
                                FROM dbo.Time_Entry
                                    INNER JOIN dbo.TE_Status ON TE_Status.TE_Status_ID = Time_Entry.TE_Status_ID
                                WHERE SR_Service_RecID IN (" + string.Join(",", idsMap.Keys) + ")";

            foreach (var k in idsMap.Keys)
                cmd.Parameters.AddWithValue(k, idsMap[k]);

            var results = new Dictionary<int, List<TimeEntry>>();
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    int ticketId = (int)reader["SR_Service_RecID"];
                    TimeEntry e = null;
                    try
                    {
                        e = new TimeEntry(reader);
                    }
                    catch (Exception ex)
                    {
                        // TODO: log
                    }

                    if (e != null)
                    {
                        List<TimeEntry> entries = null;
                        if (!results.ContainsKey(ticketId))
                        {
                            entries = new List<TimeEntry>();
                            results.Add(ticketId, entries);
                        }
                        else
                        {
                            entries = results[ticketId];
                        }

                        entries.Add(e);
                    }
                }
            }

            return results;
        }
        /// <summary>
        /// https://github.com/toggl/toggl_api_docs/blob/master/chapters/time_entries.md#update-a-time-entry
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public async System.Threading.Tasks.Task<TimeEntry> Edit(TimeEntry obj)
        {
            var url = string.Format(ApiRoutes.TimeEntry.TimeEntryUrl, obj.Id);

            var response = await ToggleSrv.Put(url, obj.ToJson());
            var timeEntry = response.GetData<TimeEntry>();

            return timeEntry;
        }
示例#26
0
 public void AddTimeEntry(TimeEntry timeEntry)
 {
     _context.TimeEntries.Add(timeEntry);
 }
示例#27
0
        private void safeSetCurrentlyRunningTimeEntry(ITimeEntry timeEntry)
        {
            var next = timeEntry == null ? null : TimeEntry.Clean(timeEntry);

            currentTimeEntrySubject.OnNext(next);
        }
示例#28
0
        public void GetTimeEntriesByTaskId()
        {
			var task1 = TaskService.Add(new Task
			{
				IsActive = true,
				Name = "task1",
				EstimatedSeconds = 3600,
				WorkspaceId = DefaultWorkspaceId,
				ProjectId = DefaultProjectId
			});
			Assert.IsNotNull(task1);

			var task2 = TaskService.Add(new Task
			{
				IsActive = true,
				Name = "task2",
				EstimatedSeconds = 3600,
				WorkspaceId = DefaultWorkspaceId,
				ProjectId = DefaultProjectId
			});
			Assert.IsNotNull(task2);

			var timeEntryService = new TimeEntryService(Constants.ApiToken);
            for (int i = 0; i < 3; i++)
            {
                var timeEntry = new TimeEntry()
                {
                    IsBillable = true,
                    CreatedWith = "TimeEntryTestAdd",
                    Description = "Test Desc" + DateTime.Now.Ticks,
                    Duration = 900,
                    Start = DateTime.Now.AddDays(-i).ToIsoDateStr(),
                    Stop = DateTime.Now.AddDays(-i).AddMinutes(20).ToIsoDateStr(),
                    WorkspaceId = DefaultWorkspaceId,
                    TaskId = task1.Id
                };
                var expTimeEntry = timeEntryService.Add(timeEntry);
                Assert.IsNotNull(expTimeEntry);
            }

			for (int i = 0; i < 3; i++)
			{
				var timeEntry = new TimeEntry()
				{
					IsBillable = true,
					CreatedWith = "TimeEntryTestAdd",
					Description = "Test Desc" + DateTime.Now.Ticks,
					Duration = 900,
					Start = DateTime.Now.AddDays(-i).ToIsoDateStr(),
					Stop = DateTime.Now.AddDays(-i).AddMinutes(20).ToIsoDateStr(),
					WorkspaceId = DefaultWorkspaceId,
					TaskId = task2.Id
				};
				var expTimeEntry = timeEntryService.Add(timeEntry);
				Assert.IsNotNull(expTimeEntry);
			}

			var standardParams = new DetailedReportParams()
			{
				UserAgent = "TogglAPI.Net",
				WorkspaceId = DefaultWorkspaceId,
				Since = DateTime.Now.AddYears(-1).ToIsoDateStr(),
				TaskIds = string.Format("{0},{1}", task1.Id.Value, task2.Id.Value)
			};

            var result = ReportService.Detailed(standardParams);
            Assert.AreEqual(result.Data.Count, 6);
            Assert.AreEqual(result.TotalCount, 6);

	        standardParams.TaskIds = task1.Id.Value.ToString();

			result = ReportService.Detailed(standardParams);
			Assert.AreEqual(result.Data.Count, 3);
			Assert.AreEqual(result.TotalCount, 3);

        }
        public async Task <bool> Add(TimeEntry entry)
        {
            var response = await _redmineClient.AddTimeEntry(new AddTimeEntryRequest(entry));

            return(response);
        }
 protected override IDatabaseTimeEntry CopyFrom(IDatabaseTimeEntry entity)
 => TimeEntry.From(entity);
 protected override IDatabaseTimeEntry CreateUnsyncableFrom(IDatabaseTimeEntry entity, string reason)
 => TimeEntry.Unsyncable(entity, reason);
示例#32
0
        public Log Parse(IEnumerable <string> lines)
        {
            var lineList = lines as string[] ?? lines.ToArray();

            if (!lineList.Any())
            {
                return(null);
            }

            var       log         = new Log();
            var       lineNumber  = -1;
            Day       currentDay  = null;
            TimeEntry currentTime = null;

            foreach (var line in lineList)
            {
                lineNumber++;

                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                Debug.WriteLine("Parsing Line {0}: {1}", lineNumber, line);

                var tokens = _lexer.Process(lineNumber, line);

                foreach (var token in tokens)
                {
                    switch (token.TokenType)
                    {
                    case TokenType.Date:
                        currentDay = new Day(lineNumber, (DateTime)token.Value);
                        log.Days.Add(currentDay);
                        break;

                    case TokenType.TimePeriod:
                        currentTime = new TimeEntry((Period)token.Value);
                        if (currentDay != null)
                        {
                            currentDay.TimeEntries.Add(currentTime);
                        }
                        break;

                    case TokenType.ProjectName:
                        if (currentTime != null)
                        {
                            currentTime.ProjectName = Convert.ToString(token.Value);
                        }
                        break;

                    case TokenType.ProjectComment:
                        if (currentTime != null)
                        {
                            currentTime.AddComment(Convert.ToString(token.Value));
                        }
                        break;
                    }
                }
            }

            return(log);
        }
示例#33
0
        private TimeEntry GetTimeByHeight(Graphics g, Renderer renderer, TimeEntry start, int height)
        {
            var fillUpMinutes = (byte)(60 - start.Minutes);
            var restMinutes   = attrs.EndTime.Minutes;

            var headerHeight = renderer.GetHeight(g, default, default, true);
        private TimeEntry SaveLocalCopy(string releaseNum, MavenlinkTimeEntry mlEntry, TimeEntry existingLocalRecord)
        {
            if (existingLocalRecord == null)
            {
                // new record in ML, no local copy
                var newLocalRecord = this.CreateTimeEntry(releaseNum, mlEntry);
                Database.TimeEntries.Add(newLocalRecord);

                return(newLocalRecord);
            }
            else if (mlEntry.MavenlinkUpdatedAt > existingLocalRecord.LocallyUpdatedAt)
            {
                // exists locally but ML is newer; replace local copy.
                // HACK: EF doesn't give us control over the sequence in which operations are flushed, so a .Remove() followed by .Add() will throw
                // a PK exception b/c the insert gets executed first. So instead, we just do an update
                // It would be better to do a drop/create so that we don't have to worry about columns being added in
                // the future not being part of the update statement
                existingLocalRecord.ProjectIdOrig           = mlEntry.ProjectId;
                existingLocalRecord.ProjectIdOverride       = mlEntry.ProjectId;
                existingLocalRecord.ProjectTitleOrig        = mlEntry.ProjectTitle;
                existingLocalRecord.ProjectTitleOverride    = mlEntry.ProjectTitle;
                existingLocalRecord.TaskIdOrig              = mlEntry.TaskId;
                existingLocalRecord.TaskIdOverride          = mlEntry.TaskId;
                existingLocalRecord.DatePerformed           = mlEntry.DatePerformed;
                existingLocalRecord.DurationMinutesOrig     = mlEntry.DurationMinutes;
                existingLocalRecord.DurationMinutesOverride = mlEntry.DurationMinutes;
                existingLocalRecord.NotesOrig             = mlEntry.Notes;
                existingLocalRecord.NotesOverride         = mlEntry.Notes;
                existingLocalRecord.Billable              = mlEntry.Billable;
                existingLocalRecord.SourceRecordCreatedAt = mlEntry.MavenlinkCreatedAt;
                existingLocalRecord.SourceRecordUpdatedAt = mlEntry.MavenlinkUpdatedAt;
                existingLocalRecord.LocallyUpdatedAt      = DateTime.Now;

                return(existingLocalRecord);
            }
            else if (existingLocalRecord.LocallyUpdatedAt >= mlEntry.MavenlinkUpdatedAt)
            {
                // exists locally and local copy was updated more recently; ignore the server record
                return(existingLocalRecord);
            }
            else
            {
                throw new NotImplementedException("Should not get here: can't figure out how to merge server data w/ local data");
            }
        }
示例#35
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            errProv.Clear();

            List <ValidatableIntStringPair> exceptionItems = new List <ValidatableIntStringPair>();

            TimeEntry savedItem = null;

            //validate
            List <ValidationMessage> errors = OperationsReadWrite.SaveTimeEntry(
                new ValidatableParameter <Guid> {
                Value = m_lastTimeEntry == null ? Guid.Empty : m_lastTimeEntry.TimeEntryId, Source = null
            },
                new ValidatableParameter <Guid> {
                Value = m_currUser.UserId, Source = null
            },
                new ValidatableParameter <Guid> {
                Value = m_lastTimeEntry.ProjectId, Source = lblProjectVal
            },
                new ValidatableParameter <Guid> {
                Value = m_lastTimeEntry.TaskId, Source = lblTaskVal
            },
                new ValidatableParameter <string> {
                Value = txtDetails.Text, Source = txtDetails
            },
                new ValidatableParameter <DateTime?> {
                Value = dtpStart.Value, Source = dtpStart
            },
                new ValidatableParameter <DateTime?> {
                Value = dtpEnd.Value, Source = dtpEnd
            },
                new ValidatableParameter <int> {
                Value = Convert.ToInt32(nudExc1.Value), Source = nudExc1
            },
                new ValidatableParameter <string> {
                Value = txtExc1.Text, Source = txtExc1
            },
                out savedItem);

            if (errors.Count > 0)
            {
                //set up the list of controls that may have errors associated
                List <Control> validatableControls = new List <Control>();
                validatableControls.Add(lblProjectVal);
                validatableControls.Add(lblTaskVal);
                validatableControls.Add(dtpStart);
                validatableControls.Add(dtpEnd);
                validatableControls.Add(nudExc1);
                validatableControls.Add(txtExc1);

                //hook up errors to controls
                foreach (ValidationMessage currError in errors)
                {
                    if (currError.Source != null)
                    {
                        bool found     = false;
                        int  currIndex = 0;
                        while (!found && currIndex < validatableControls.Count)
                        {
                            if (validatableControls[currIndex] == currError.Source)
                            {
                                found = true;
                                errProv.SetError(validatableControls[currIndex], currError.MessageText);
                            }
                            currIndex++;
                        }

                        if (!found)
                        {
                            errProv.SetError(btnSave, currError.MessageText);
                        }
                    }
                    else
                    {
                        errProv.SetError(btnSave, currError.MessageText);
                    }
                }
            }
            else
            {
                SavedEntry   = savedItem;
                WasConfirmed = true;
                this.Close();
            }
        }
示例#36
0
        public async Task Stop()
        {
            User user = database.Users
                        .AsQueryable()
                        .FirstOrDefault(u => u.DiscordId == Context.User.Id.ToString());

            if (user == null)
            {
                await Context.Message.ReplyAsync("Your Discord account is not currently linked to an NTime account. Use `!login` to link your accounts together.");

                return;
            }

            List <Timer> timers = database.Timers
                                  .AsQueryable()
                                  .Where(timer => timer.User.Id == user.Id)
                                  .ToList();

            if (timers.Count == 0)
            {
                await Context.Message.ReplyAsync("There are no active timers to stop.");

                return;
            }
            else if (timers.Count == 1)
            {
                DateTime timeEntryCreationTime = DateTime.UtcNow;

                TimeEntry timeEntry = new TimeEntry {
                    CreatedTime  = timeEntryCreationTime,
                    Notes        = timers[0].Notes,
                    Project      = timers[0].Project,
                    LastModified = timeEntryCreationTime,
                    User         = user,
                    Length       = Math.Round((timeEntryCreationTime - timers[0].StartTime).TotalHours, 2),
                    Day          = timeEntryCreationTime
                };

                database.TimeEntries.Add(timeEntry);

                database.Timers.Remove(timers[0]);

                await database.SaveChangesAsync();

                await Context.Message.ReplyAsync("Timer stopped for the project **" + timers[0].Project.Name + "**, and a new time entry with " + timeEntry.Length + " hours on it has been added.");

                return;
            }

            timers.Sort((a, b) => a.Project.Name.CompareTo(b.Project.Name));

            EmbedBuilder embedBuilder = new EmbedBuilder()
            {
                Color       = new Color(35, 45, 154),
                Title       = "Active Timers",
                Description = "Multiple projects with active timers were found, please select one to stop:"
            };

            for (int i = 0; i < timers.Count; i++)
            {
                embedBuilder.AddField(field => {
                    field.Name     = timers[i].Project.Name + " (Active for " + Math.Round((DateTime.UtcNow - timers[i].StartTime).TotalHours, 2) + " hours)";
                    field.Value    = "!stop " + (i + 1);
                    field.IsInline = false;
                });
            }

            embedBuilder.WithFooter(footer => {
                footer.Text    = "(you can also stop a timer directly using !stop [project name])";
                footer.IconUrl = "";
            });

            await Context.Message.ReplyAsync("", false, embedBuilder.Build());

            return;
        }
示例#37
0
 public TrainRenderer(IEnumerable <Station> stations, Timetable tt, Margins margin, TimeEntry startTime, Dictionary <Station, StationRenderProps> stationOffsets, Days renderDays)
 {
     this.stations       = stations;
     this.tt             = tt;
     this.margin         = margin;
     this.startTime      = startTime;
     this.stationOffsets = stationOffsets;
     this.renderDays     = renderDays;
     attrs = new TimetableStyle(tt);
 }
示例#38
0
 public IActionResult Update(long id, [FromBody] TimeEntry timeEntry)
 {
     return(_repository.Contains(id) ? (IActionResult)Ok(_repository.Update(id, timeEntry)) : NotFound());
 }
示例#39
0
 private Project?DeterminePsaProject(TimeEntry entry)
 {
     return(entry.Project.StartsWith("Home Intelligence") || entry.Project.StartsWith("HI") ? Project.HomeIntelligence
         : entry.Project.StartsWith("MyWay Digital Experience") ? Project.MyWay
         : (Project?)null);
 }
示例#40
0
        public IActionResult Create([FromBody] TimeEntry timeEntry)
        {
            var createdTimeEntry = _repository.Create(timeEntry);

            return(CreatedAtRoute("GetTimeEntry", new { id = createdTimeEntry.Id }, createdTimeEntry));
        }
示例#41
0
 public void UpdateTimeEntry(TimeEntry timeEntry)
 {
     _context.TimeEntries.Update(timeEntry);
 }
示例#42
0
 public void Add(TimeEntry timeEntry)
 {
     this._repository.Add(timeEntry);
     this._repository.Save();
 }
示例#43
0
 public void RemoveTimeEntry(TimeEntry timeEntry)
 {
     _context.TimeEntries.Remove(timeEntry);
 }
 protected override IDatabaseTimeEntry CreateCleanEntityFrom(IDatabaseTimeEntry entity)
 => TimeEntry.Clean(entity);
示例#45
0
	    public void Insert(int Timesheetid,int Day,string Timein,string Timeout,string Notes,bool IsDeleted,DateTime? CreatedOn,string CreatedBy,DateTime? ModifiedOn,string ModifiedBy)
	    {
		    TimeEntry item = new TimeEntry();
		    
            item.Timesheetid = Timesheetid;
            
            item.Day = Day;
            
            item.Timein = Timein;
            
            item.Timeout = Timeout;
            
            item.Notes = Notes;
            
            item.IsDeleted = IsDeleted;
            
            item.CreatedOn = CreatedOn;
            
            item.CreatedBy = CreatedBy;
            
            item.ModifiedOn = ModifiedOn;
            
            item.ModifiedBy = ModifiedBy;
            
	    
		    item.Save(UserName);
	    }
示例#46
0
 public static TimeEntryDto ToDto(this TimeEntry timeEntry)
 {
     return(new TimeEntryDto
     {
     });
 }
        /// <summary>
        /// 
        /// https://github.com/toggl/toggl_api_docs/blob/master/chapters/time_entries.md#create-a-time-entry
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public async System.Threading.Tasks.Task<TimeEntry> Add(TimeEntry obj)
        {
            var url = ApiRoutes.TimeEntry.TimeEntriesUrl;

            var response = await ToggleSrv.Post(url, obj.ToJson());
            var timeEntry = response.GetData<TimeEntry>();

            return timeEntry;
        }
示例#48
0
 protected override IThreadSafeTimeEntry Convert(IDatabaseTimeEntry entity)
 => TimeEntry.From(entity);
示例#49
0
 private void TaskStarted(TimeEntry timeEntry)
 {
     TryInitializeTimer(_appSettings.ActiveTimeNotificationInterval, ActiveTimeTick);
 }
示例#50
0
 public void MapTo(TimeEntry timeEntry)
 {
     timeEntry.EntryDate   = EntryDate;
     timeEntry.Hours       = Hours;
     timeEntry.Description = Description;
 }
示例#51
0
        private void CommitChange(Zeit temp)
        {
            var issue = Manager.GetObject<Issue>(temp.Ticket.ToString(CultureInfo.InvariantCulture), null);

             if (issue == null)
             {
            MessageBox.Show("Das Ticket ist im Redmine nicht vorhanden");
            return;
             }

             var project = Manager.GetObject<Project>(issue.Project.Id.ToString(CultureInfo.InvariantCulture), null);
             if (project != null && project.Name == "Demo")
             {
            var entry = new TimeEntry
                           {
                              Comments = temp.Kommentar,
                              Hours = SerializableTimeSpan.ToDecimal(temp.Dauer),
                              Issue = new IdentifiableName { Id = temp.Ticket }
                           };
            TaskLabel = GetMessage(Manager.CreateObject(entry));
             }
        }
 private static HttpContent SerializePayload(TimeEntry timeEntry) => new StringContent(
     JsonConvert.SerializeObject(timeEntry),
     Encoding.UTF8,
     "application/json"
 );
        protected virtual void Rebind()
        {
            ResetTrackedObservables();

            if (TimeEntry == null || !canRebind)
            {
                return;
            }

            DateTime startTime;
            var      useTimer = TimeEntry.StartTime.IsMinValue();

            if (useTimer)
            {
                startTime = Time.Now;

                DurationTextView.Text = TimeSpan.Zero.ToString();

                // Make sure that we display accurate time:
                handler.RemoveCallbacks(Rebind);
                handler.PostDelayed(Rebind, 5000);
            }
            else
            {
                startTime = TimeEntry.StartTime.ToLocalTime();

                var duration = TimeEntry.GetDuration();
                DurationTextView.Text = TimeSpan.FromSeconds((long)duration.TotalSeconds).ToString();

                if (TimeEntry.State == TimeEntryState.Running)
                {
                    handler.RemoveCallbacks(Rebind);
                    handler.PostDelayed(Rebind, 1000 - duration.Milliseconds);
                }
            }

            StartTimeEditText.Text = startTime.ToDeviceTimeString();

            // Only update DescriptionEditText when content differs, else the user is unable to edit it
            if (!descriptionChanging && DescriptionEditText.Text != TimeEntry.Description)
            {
                DescriptionEditText.Text = TimeEntry.Description;
                DescriptionEditText.SetSelection(DescriptionEditText.Text.Length);
            }
            DescriptionEditText.SetHint(useTimer
                                         ? Resource.String.CurrentTimeEntryEditDescriptionHint
                                         : Resource.String.CurrentTimeEntryEditDescriptionPastHint);

            if (TimeEntry.StopTime.HasValue)
            {
                StopTimeEditText.Text       = TimeEntry.StopTime.Value.ToLocalTime().ToDeviceTimeString();
                StopTimeEditText.Visibility = ViewStates.Visible;
            }
            else
            {
                StopTimeEditText.Text = Time.Now.ToDeviceTimeString();
                if (TimeEntry.StartTime.IsMinValue() || TimeEntry.State == TimeEntryState.Running)
                {
                    StopTimeEditText.Visibility  = ViewStates.Invisible;
                    StopTimeEditLabel.Visibility = ViewStates.Invisible;
                }
                else
                {
                    StopTimeEditLabel.Visibility = ViewStates.Visible;
                    StopTimeEditText.Visibility  = ViewStates.Visible;
                }
            }

            if (TimeEntry.Project != null)
            {
                ProjectEditText.Text = TimeEntry.Project.Name;
                if (TimeEntry.Project.Client != null)
                {
                    ProjectBit.SetAssistViewTitle(TimeEntry.Project.Client.Name);
                }
                else
                {
                    ProjectBit.DestroyAssistView();
                }
            }
            else
            {
                ProjectEditText.Text = String.Empty;
                ProjectBit.DestroyAssistView();
            }

            BillableCheckBox.Checked = !TimeEntry.IsBillable;
            if (TimeEntry.IsBillable)
            {
                BillableCheckBox.SetText(Resource.String.CurrentTimeEntryEditBillableChecked);
            }
            else
            {
                BillableCheckBox.SetText(Resource.String.CurrentTimeEntryEditBillableUnchecked);
            }
            if (TimeEntry.Workspace == null || !TimeEntry.Workspace.IsPremium)
            {
                BillableCheckBox.Visibility = ViewStates.Gone;
            }
            else
            {
                BillableCheckBox.Visibility = ViewStates.Visible;
            }
        }
示例#54
0
        public void GetUserFromRedmine(Dictionary <string, string> bossName) //params string[] noNameForReport)
        {
            NameValueCollection parametr;

            countTotalRecord = 0;
            curReadRecord    = 0;

            ClearLists();

            progressBar.InvokeIfNeeded(delegate { progressBar.DisplayStyle = ProgressBarDisplayText.CustomText; });
            progressBar.InvokeIfNeeded(delegate { progressBar.CustomText = "Загрузка записей, подождите пожалуйста."; });
            progressBar.InvokeIfNeeded(delegate { progressBar.Minimum = 0; });


            //SetInitProgBar(progressBar, 0, 5, 1);

            try
            {
                //parametr = new NameValueCollection { { "user_id", "*" } };
                //countTotalRecord += redmineManager.GetObjects<User>(parametr).Count;
                //progressBar.InvokeIfNeeded(delegate { progressBar.PerformStep(); });
                //progressBar.InvokeIfNeeded(delegate { progressBar.CustomText = "Список № " + progressBar.Value + "/5"; });

                //parametr = new NameValueCollection { { "group_id", "*" } };
                //countTotalRecord += redmineManager.GetObjects<Group>(parametr).Count;
                //progressBar.InvokeIfNeeded(delegate { progressBar.PerformStep(); });
                //progressBar.InvokeIfNeeded(delegate { progressBar.CustomText = "Список № " + progressBar.Value + "/5"; });

                //parametr = new NameValueCollection { { "status_id", "*" } };
                //countTotalRecord += redmineManager.GetObjects<Issue>(parametr).Count;
                //progressBar.InvokeIfNeeded(delegate { progressBar.PerformStep(); });
                //progressBar.InvokeIfNeeded(delegate { progressBar.CustomText = "Список № " + progressBar.Value + "/5"; });

                //parametr = new NameValueCollection { { "project_id", "*" } };
                //countTotalRecord += redmineManager.GetObjects<Project>(parametr).Count;
                //progressBar.InvokeIfNeeded(delegate { progressBar.PerformStep(); });
                //progressBar.InvokeIfNeeded(delegate { progressBar.CustomText = "Список № " + progressBar.Value + "/5"; });

                //parametr = new NameValueCollection { { "user_id", "*" } };
                //countTotalRecord += redmineManager.GetObjects<TimeEntry>(parametr).Count;
                //progressBar.InvokeIfNeeded(delegate { progressBar.PerformStep(); });
                //progressBar.InvokeIfNeeded(delegate { progressBar.CustomText = "Список № " + progressBar.Value + "/5"; });

                //progressBar.InvokeIfNeeded(delegate { progressBar.Value = 0; });
                //progressBar.InvokeIfNeeded(delegate { progressBar.Maximum = countTotalRecord; });
                //progressBar.InvokeIfNeeded(delegate { progressBar.Step = 1; });

                parametr = new NameValueCollection {
                    { "user_id", "*" }
                };
                List <User> listUserRedm = redmineManager.GetObjects <User>(parametr);

                countTotalRecord = listUserRedm.Count;
                SetInitProgBar(progressBar, 0, countTotalRecord, 1);
                foreach (var user in listUserRedm)
                {
                    if (user.IsCustomFieldEqual("Учет трудозатратах/месяц"))
                    {
                        listUser.Add(user);
                        //userRedmine.listIssue = this.listIssue;

                        UserRedmine userRedmine = new UserRedmine(this.monthValueHours);
                        userRedmine.bossName    = bossName;
                        userRedmine.Value       = user;
                        userRedmine.listProject = this.listProject;

                        curReadRecord++;
                        progressBar.InvokeIfNeeded(delegate { progressBar.PerformStep(); });
                        progressBar.InvokeIfNeeded(delegate
                        {
                            progressBar.CustomText = "Запись № " + progressBar.Value +
                                                     "/ " + countTotalRecord;
                        });

                        listUserRedmine.Add(userRedmine);

                        Debug.WriteLine(curReadRecord);
                    }


                    //parametr = new NameValueCollection { { "user_id", user.Id.ToString() } };
                    //int count = redmineManager.GetObjects<TimeEntry>(parametr).Count;
                    //if (count > 0)
                    //{
                    //    UserRedmine userRedmine = new UserRedmine();
                    //    userRedmine.Value = user;
                    //    listUserRedmine.Add(userRedmine);
                    //    Console.WriteLine("Name = {0}, Count time entry = {1}", user.LastName, count);
                    //}
                }

                parametr = new NameValueCollection {
                    { "group_id", "*" }
                };
                List <Group> listGroupRedm = redmineManager.GetObjects <Group>(parametr);

                countTotalRecord = listGroupRedm.Count;
                SetInitProgBar(progressBar, 0, countTotalRecord, 1);
                foreach (Group group in listGroupRedm)
                {
                    curReadRecord++;
                    progressBar.InvokeIfNeeded(delegate { progressBar.PerformStep(); });
                    progressBar.InvokeIfNeeded(delegate
                    {
                        progressBar.CustomText = "Запись № " + progressBar.Value +
                                                 "/ " + countTotalRecord;
                    });


                    UserGroup userGroup = new UserGroup(group.Name, group.Id);
                    listUserRedm = redmineManager.GetObjects <User>(new NameValueCollection {
                        { "group_id", group.Id.ToString() }
                    });
                    foreach (User user in listUserRedm)
                    {
                        UserRedmine userRedmine = listUserRedmine.Find(x => x.Value.Id == user.Id);
                        if (userRedmine != null)
                        {
                            userRedmine.listUserGroup.Add(userGroup);
                        }
                    }
                }

                //parametr = new NameValueCollection { { "status_id", "*" } };//{ "status_id", "*" }
                //Issue issueIdRedm = redmineManager.GetObject<Issue>("1435", parametr);

                Issue issue_jornals = redmineManager.GetObject <Issue>("1435", new NameValueCollection {
                    { "include", "journals" }
                });
                if (issue_jornals != null)
                {
                    foreach (var journal in issue_jornals.Journals)
                    {
                        string note = journal.Notes;
                        if (!note.Equals(""))
                        {
                            MonthHours monthHours = new MonthHours(note);
                            listMonthHours.Add(monthHours);
                        }
                    }
                }

                parametr = new NameValueCollection {
                    { "created_on", ">=" + GetFirstDateCurYear() }
                };                                                                                    //{ "status_id", "*" }

                List <Issue> listIssueRedm = redmineManager.GetObjects <Issue>(parametr);

                countTotalRecord = listIssueRedm.Count;
                SetInitProgBar(progressBar, 0, countTotalRecord, 1);
                foreach (Issue issue in listIssueRedm)
                {
                    listIssue.Add(issue);
                    curReadRecord++;
                    progressBar.InvokeIfNeeded(delegate { progressBar.PerformStep(); });
                    progressBar.InvokeIfNeeded(delegate
                    {
                        progressBar.CustomText = "Запись № " + progressBar.Value +
                                                 "/ " + countTotalRecord;
                    });
                    Debug.WriteLine(curReadRecord);
                    Debug.WriteLine(issue.CreatedOn.Value);
                    //if (issue.Id == 1435)
                    //{
                    //    Issue issue_jornals = redmineManager.GetObject<Issue>(issue.Id.ToString(),
                    //                                                          new NameValueCollection { { "include", "journals" } });

                    //    foreach (var journal in issue_jornals.Journals)
                    //    {
                    //        string note = journal.Notes;
                    //        if (!note.Equals(""))
                    //        {
                    //            MonthHours monthHours = new MonthHours(note);
                    //            listMonthHours.Add(monthHours);
                    //        }
                    //    }
                    //}
                }

                parametr = new NameValueCollection {
                    { "project_id", "*" }
                };
                List <Project> listProjectRedm = redmineManager.GetObjects <Project>(parametr);

                countTotalRecord = listProjectRedm.Count;
                SetInitProgBar(progressBar, 0, countTotalRecord, 1);
                foreach (Project project in listProjectRedm)
                {
                    listProject.Add(project);
                    curReadRecord++;
                    progressBar.InvokeIfNeeded(delegate { progressBar.PerformStep(); });
                    progressBar.InvokeIfNeeded(delegate
                    {
                        progressBar.CustomText = "Запись № " + progressBar.Value +
                                                 "/ " + countTotalRecord;
                    });
                }


                parametr = new NameValueCollection {
                    { "spent_on", ">=" + GetFirstDateCurYear() }
                };                                                                                  //{ "user_id", "*" }
                List <TimeEntry> listTimeEntryRedm = redmineManager.GetObjects <TimeEntry>(parametr);

                //List<TimeEntry> listTimeEntryUnique = new List<TimeEntry>();

                TimeEntry timeUniqe;

                for (int i = 0; i < listTimeEntryRedm.Count; i++)
                {
                    TimeEntry timeI = listTimeEntryRedm[i];
                    timeUniqe = timeI;

                    int j = i + 1;
                    while (j < listTimeEntryRedm.Count)
                    {
                        TimeEntry timeJ = listTimeEntryRedm[j];
                        if ((timeI.User.Id == timeJ.User.Id) &
                            (timeI.Project.Id == timeJ.Project.Id) &
                            (timeI.Activity.Id == timeJ.Activity.Id) &
                            (timeI.Id != timeJ.Id) &
                            (timeI.SpentOn.Value.Date.Month == timeJ.SpentOn.Value.Date.Month))
                        {
                            // TODO добавить поиск даты старта и даты финиша суммарной задчи timeI
                            DateTime startDateTimeI  = timeI.GetDateValue("Дата старта", TypeDates.Start);
                            DateTime finishDateTimeI = timeI.GetDateValue("Дата завершения", TypeDates.Finish);

                            DateTime startDateTimeJ  = timeJ.GetDateValue("Дата старта", TypeDates.Start);
                            DateTime finishDateTimeJ = timeJ.GetDateValue("Дата завершения", TypeDates.Finish);

                            if (startDateTimeI.CompareTo(startDateTimeJ) > 0)
                            {
                                timeI.SetDateValue("Дата старта", startDateTimeJ);
                            }

                            if (finishDateTimeI.CompareTo(finishDateTimeJ) < 0)
                            {
                                timeI.SetDateValue("Дата завершения", finishDateTimeJ);
                            }

                            timeI.Hours += timeJ.Hours;
                            listTimeEntryRedm.Remove(timeJ);
                        }
                        else
                        {
                            j++;
                        }
                    }
                }

                countTotalRecord = listTimeEntryRedm.Count;
                SetInitProgBar(progressBar, 0, countTotalRecord, 1);

                var qTimeEntryAll = from time in listTimeEntryRedm
                                    from userRedmine in listUserRedmine
                                    from project in listProject
                                    where time.User.Id == userRedmine.Value.Id
                                    where ((time.Project.Id == project.Id) & project.IsPublic)
                                    select new
                {
                    listIssue   = userRedmine.listIssue,
                    listProject = userRedmine.listProject,
                    userRedmine = userRedmine,
                    listUser    = listUser,
                    Value       = time
                };

                foreach (var time in qTimeEntryAll)
                {
                    UserTimeEntry userTimeEntry = new UserTimeEntry(time.listIssue, time.listProject,
                                                                    time.userRedmine, time.listUser);
                    userTimeEntry.Value = time.Value;
                    time.userRedmine.listUserTimeEntry.Add(userTimeEntry);
                }

                //foreach (var time in listTimeEntryRedm)
                //{
                //    UserRedmine userRedmine = listUserRedmine.Find(x => x.Value.Id == time.User.Id);
                //    Project project = listProject.Find(x => x.Id == time.Project.Id);
                //    curReadRecord++;
                //    progressBar.InvokeIfNeeded(delegate { progressBar.PerformStep(); });
                //    progressBar.InvokeIfNeeded(delegate {progressBar.CustomText = "Запись № " + progressBar.Value +
                //                                        "/ " + countTotalRecord;
                //    });
                //    if (userRedmine != null)
                //    {
                //        if (project != null)
                //        {
                //            if (project.IsPublic)
                //            {
                //                UserTimeEntry userTimeEntry = new UserTimeEntry(userRedmine.listIssue, userRedmine.listProject,
                //                                                                userRedmine, listUser);
                //                userTimeEntry.Value = time;
                //                userRedmine.listUserTimeEntry.Add(userTimeEntry);
                //            }
                //        }
                //    }
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error - " + ex.Message);
            }

            listUserRedmine.Sort();
        }
示例#55
0
    public static TimeEntry parse(string date, string times)
    {
        string[] timeIO = Regex.Split(times, " To ");
        TimeEntry e = new TimeEntry();
        string start = date + " " + timeIO[0];
        string end = date + " " + timeIO[1];

        //Debug.WriteLine("start = " + start);
        //Debug.WriteLine("end = " + end);
        e.TimeIn = DateTime.ParseExact(start, "MM/dd/yyyy HHmm", CultureInfo.InvariantCulture);
        e.TimeOut = DateTime.ParseExact(end, "MM/dd/yyyy HHmm", CultureInfo.InvariantCulture);

        return e;
    }
        private async Task <TimeEntryResult> TrackTime(TimeEntry entry, Guid?storyId, bool?isStoryComplete)
        {
            _logger.LogInformation(GetLogMessage("Tracking time entry..."));

            var retVal = new TimeEntryResult();

            var contract = await _contractService.Repository.Queryable()
                           .Include(x => x.Project)
                           .ThenInclude(x => x.CustomerAccount)
                           .Include(x => x.Project)
                           .ThenInclude(x => x.Proposal)
                           .Include(x => x.ProviderOrganization)
                           .ThenInclude(x => x.Organization)
                           .Include(x => x.MarketerOrganization)
                           .ThenInclude(x => x.Organization)
                           .Include(x => x.RecruiterOrganization)
                           .ThenInclude(x => x.Organization)
                           .Include(x => x.OrganizationContractor)
                           .Where(x => x.Id == entry.ContractId)
                           .FirstOrDefaultAsync();

            if (contract.Status == ContractStatus.Paused || contract.Status == ContractStatus.Inactive)
            {
                retVal.ErrorMessage = "You cannot log time if contract is paused or ended";
                _logger.LogInformation(GetLogMessage(retVal.ErrorMessage));
                return(retVal);
            }

            if (contract.Project.Proposal == null)
            {
                retVal.ErrorMessage = "Proposal not found for the project";
                _logger.LogInformation(GetLogMessage(retVal.ErrorMessage));
                return(retVal);
            }

            if (contract.Project.Proposal.Status != ProposalStatus.Accepted)
            {
                retVal.ErrorMessage = "Proposal not accepted for the project";
                _logger.LogInformation(GetLogMessage(retVal.ErrorMessage));
                return(retVal);
            }

            var autoApproveProject    = contract.Project.AutoApproveTimeEntries;
            var autoApproveContractor = contract.OrganizationContractor.AutoApproveTimeEntries;
            var autoApprove           = autoApproveProject || autoApproveContractor;

            entry.ProviderAgencyOwnerId   = contract.ProviderOrganization.Organization.CustomerId;
            entry.MarketingAgencyOwnerId  = contract.MarketerOrganization.Organization.CustomerId;
            entry.RecruitingAgencyOwnerId = contract.RecruiterOrganization.Organization.CustomerId;

            entry.ProviderOrganizationId   = contract.ContractorOrganizationId;
            entry.MarketingOrganizationId  = contract.MarketerOrganizationId;
            entry.RecruitingOrganizationId = contract.RecruiterOrganizationId;

            entry.ContractorId           = contract.ContractorId;
            entry.MarketerId             = contract.MarketerId;
            entry.RecruiterId            = contract.RecruiterId;
            entry.ProjectManagerId       = contract.ProjectManagerId;
            entry.AccountManagerId       = contract.AccountManagerId;
            entry.ProjectId              = contract.ProjectId;
            entry.CustomerId             = contract.Project.CustomerId;
            entry.CustomerOrganizationId = contract.Project.CustomerOrganizationId;
            entry.Status  = autoApprove ? TimeStatus.Approved : TimeStatus.Logged;
            entry.StoryId = storyId;
            entry.InstantAccountManagerStream   = contract.AccountManagerStream;
            entry.InstantProjectManagerStream   = contract.ProjectManagerStream;
            entry.InstantRecruiterStream        = contract.RecruiterStream;
            entry.InstantMarketerStream         = contract.MarketerStream;
            entry.InstantContractorStream       = contract.ContractorStream;
            entry.InstantSystemStream           = contract.SystemStream;
            entry.InstantAgencyStream           = contract.AgencyStream;
            entry.InstantRecruitingAgencyStream = contract.RecruitingAgencyStream;
            entry.InstantMarketingAgencyStream  = contract.MarketingAgencyStream;

            entry.UpdatedById = _userInfo.UserId;
            entry.CreatedById = _userInfo.UserId;

            if (autoApprove)
            {
                entry.StatusTransitions.Add(new TimeEntryStatusTransition()
                {
                    Status      = TimeStatus.Approved,
                    ObjectState = ObjectState.Added
                });
            }
            else
            {
                entry.StatusTransitions.Add(new TimeEntryStatusTransition()
                {
                    Status      = TimeStatus.Logged,
                    ObjectState = ObjectState.Added
                });
            }


            var records = await Repository.InsertAsync(entry, true);


            _logger.LogDebug(GetLogMessage("{0} records updated"), records);


            if (records > 0)
            {
                bool isStoryCompleted = false;

                if (storyId.HasValue)
                {
                    _logger.LogDebug(GetLogMessage("Time entry has story: {0}"), storyId.Value);

                    var story = await _storyService.Repository
                                .Queryable()
                                .FirstOrDefaultAsync(x => x.Id == storyId.Value);

                    if (isStoryComplete.HasValue)
                    {
                        if (isStoryComplete.Value && story.Status != StoryStatus.Completed)
                        {
                            _logger.LogDebug(GetLogMessage("Story was completed"));

                            story.Status = StoryStatus.Completed;
                            story.StatusTransitions.Add(new StoryStatusTransition()
                            {
                                Status      = StoryStatus.Completed,
                                ObjectState = ObjectState.Added
                            });

                            isStoryCompleted = true;
                        }
                    }
                    else
                    {
                        _logger.LogDebug(GetLogMessage("Story was not completed"));
                        if (story.Status != StoryStatus.InProgress)
                        {
                            story.Status = StoryStatus.InProgress;
                            story.StatusTransitions.Add(new StoryStatusTransition()
                            {
                                Status      = StoryStatus.InProgress,
                                ObjectState = ObjectState.Added
                            });
                        }
                    }

                    story.TotalHoursLogged += entry.TotalHours;
                    story.ObjectState       = ObjectState.Modified;
                    story.Updated           = DateTimeOffset.UtcNow;

                    var result = _storyService.Repository.InsertOrUpdateGraph(story, true);

                    _logger.LogDebug(GetLogMessage("{0} records updated in db"), result);

                    if (result > 0)
                    {
                        retVal.Succeeded   = true;
                        retVal.TimeEntryId = entry.Id;

                        await Task.Run(() =>
                        {
                            RaiseEvent(new TimeEntryLoggedEvent()
                            {
                                TimeEntryId = entry.Id
                            });
                        });

                        if (isStoryCompleted)
                        {
                            await Task.Run(() => RaiseEvent(new StoryCompletedEvent()
                            {
                                StoryId = storyId.Value
                            }));
                        }
                    }
                }
                else
                {
                    retVal.Succeeded   = true;
                    retVal.TimeEntryId = entry.Id;
                }
            }

            return(retVal);
        }
 protected override IDatabaseTimeEntry CreateDirtyEntity(long id, DateTimeOffset lastUpdate = default(DateTimeOffset))
 => TimeEntry.Dirty(new Ultrawave.Models.TimeEntry {
     Id = id, Description = Guid.NewGuid().ToString(), At = lastUpdate
 });
示例#58
0
 private float GetTimeY(TimeEntry time) => margin.Top + ((time - startTime).GetTotalMinutes() * attrs.HeightPerHour / 60f);
示例#59
0
 public void AddTimeEntry(TimeEntry timeEntry)
 {
     // Check for duplicates
     TimeEntry c = workTajmDb.TimeEntries.FirstOrDefault(s => ((TimeEntry)s).Id == timeEntry.Id);
     if (c == null)
     {
         // Add it
         Debug.WriteLine("AddTimeEntry - New time entry, adding it to the database");
         workTajmDb.TimeEntries.InsertOnSubmit(timeEntry);
         TimeEntries.Add(timeEntry);
         workTajmDb.SubmitChanges();
     }
     else
     {
         Debug.WriteLine("AddTimeEntry - Time entry already exists");
     }
     NotifyPropertyChanged("TimeEntries");
 }
 protected override IDatabaseTimeEntry CreateDirtyEntityWithNegativeId()
 => TimeEntry.Dirty(new Ultrawave.Models.TimeEntry {
     Id = -1, Description = Guid.NewGuid().ToString()
 });