protected string GetPostedTime(object obj, object objectType, int timeTrackingEntryId)
        {
            string retval = "";

            if (obj != null && obj != DBNull.Value && objectType != null && objectType != DBNull.Value)
            {
                int objectId     = (int)obj;
                int objectTypeId = (int)objectType;

                if (objectTypeId == (int)ObjectTypes.CalendarEntry ||
                    objectTypeId == (int)ObjectTypes.Document ||
                    objectTypeId == (int)ObjectTypes.Issue ||
                    objectTypeId == (int)ObjectTypes.Task ||
                    objectTypeId == (int)ObjectTypes.ToDo)
                {
                    int minutes = TimeTrackingManager.GetPostedTimeByObject((int)objectId, (int)objectTypeId);
                    retval = Mediachase.UI.Web.Util.CommonHelper.GetHours(minutes);
                }
            }
            else if ((bool)block.Properties["AreFinancesRegistered"].Value)
            {
                TimeTrackingEntry entry = MetaObjectActivator.CreateInstance <TimeTrackingEntry>(TimeTrackingEntry.GetAssignedMetaClass(), timeTrackingEntryId);
                int minutes             = 0;
                if (entry.Properties["TotalApproved"].Value != null && entry.Properties["TotalApproved"].Value != DBNull.Value)
                {
                    minutes = Convert.ToInt32(entry.Properties["TotalApproved"].Value);
                }
                retval = Mediachase.UI.Web.Util.CommonHelper.GetHours(minutes);
            }

            return(retval);
        }
Beispiel #2
0
        protected void AddButton_Click(object sender, EventArgs e)
        {
            DateTime startDate     = DateTime.Parse(Request["uid"], CultureInfo.InvariantCulture);
            DateTime destStartDate = CHelper.GetWeekStartByDate(DTCWeek.SelectedDate);

            if (startDate.Date != destStartDate.Date)
            {
                TimeTrackingEntry[] mas      = TimeTrackingEntry.List(FilterElement.EqualElement("OwnerId", Mediachase.IBN.Business.Security.CurrentUser.UserID), FilterElement.EqualElement("StartDate", startDate));
                List <int>          entryIds = new List <int>();
                foreach (TimeTrackingEntry tte in mas)
                {
                    entryIds.Add((int)tte.PrimaryKeyId.Value);
                }
                if (entryIds.Count > 0)
                {
                    TimeTrackingManager.AddEntries(destStartDate, Mediachase.IBN.Business.Security.CurrentUser.UserID, entryIds);
                }
            }


            // Refresh parent window
            CommandParameters cp = new CommandParameters("MC_TT_CloneWeek");

            Mediachase.Ibn.Web.UI.WebControls.CommandHandler.RegisterCloseOpenedFrameScript(this.Page, cp.ToString());
        }
Beispiel #3
0
        public static void RegisterTriggers()
        {
            TriggerManager.AddTrigger(TimeTrackingBlock.GetAssignedMetaClass(),
                                      new Trigger("RecalculateProjectByTimeTrackingBlock",
                                                  "Recalculates project fields by time tracking block", false, false, true, string.Empty, "RecalculateProject"));

            TriggerManager.AddTrigger(TimeTrackingEntry.GetAssignedMetaClass(),
                                      new Trigger("RecalculateObjectByTimeTrackingEntry",
                                                  "Recalculates project fields by time tracking block", true, true, true, string.Empty, "RecalculateObject"));
        }
Beispiel #4
0
 /// <summary>
 /// Binds the TT entry.
 /// </summary>
 /// <param name="tte">The tte.</param>
 void BindTTEntry(TimeTrackingEntry tte)
 {
     Day1Time.Value = DateTime.MinValue.AddMinutes(tte.Day1);
     Day2Time.Value = DateTime.MinValue.AddMinutes(tte.Day2);
     Day3Time.Value = DateTime.MinValue.AddMinutes(tte.Day3);
     Day4Time.Value = DateTime.MinValue.AddMinutes(tte.Day4);
     Day5Time.Value = DateTime.MinValue.AddMinutes(tte.Day5);
     Day6Time.Value = DateTime.MinValue.AddMinutes(tte.Day6);
     Day7Time.Value = DateTime.MinValue.AddMinutes(tte.Day7);
 }
        private MetaView GetMetaView()
        {
            MetaView currentView = new MetaView(TimeTrackingEntry.GetAssignedMetaClass(), "FinanceProjectReport", string.Empty);

            foreach (MetaField mf in currentView.MetaClass.Fields)
            {
                currentView.AvailableFields.Add(mf);
            }

            // Total
            currentView.TotalGroupBy = new GroupByElement();
            currentView.TotalGroupBy.IsPreGroupObjectVisible  = false;
            currentView.TotalGroupBy.IsPostGroupObjectVisible = true;

            currentView.TotalGroupBy.PostGroupObjectFields.Add(new GroupByObjectField("Title", ValueSourceType.Custom, CHelper.GetResFileString("{IbnFramework.Global:_mc_Total}")));
            currentView.TotalGroupBy.PostGroupObjectFields.Add(new GroupByObjectField("DayT", ValueSourceType.Function, GroupByObjectField.SumFunction));
            currentView.TotalGroupBy.PostGroupObjectFields.Add(new GroupByObjectField("TotalApproved", ValueSourceType.Function, GroupByObjectField.SumFunction));
            currentView.TotalGroupBy.PostGroupObjectFields.Add(new GroupByObjectField("Cost", ValueSourceType.Function, GroupByObjectField.SumFunction));

            // PrimaryGroupBy, SecondaryGroupBy
            if (GroupingList.SelectedValue == GroupingWeekUser)
            {
                currentView.PrimaryGroupBy = new GroupByElement("StartDate");
                currentView.PrimaryGroupBy.PreGroupObjectFields.Add(new GroupByObjectField("Title", ValueSourceType.Field, "StartDate", false));
                currentView.SecondaryGroupBy = new GroupByElement("Owner");
                currentView.SecondaryGroupBy.PreGroupObjectFields.Add(new GroupByObjectField("Title", ValueSourceType.Field, "Owner", false));
            }
            else
            {
                currentView.PrimaryGroupBy = new GroupByElement("Owner");
                currentView.PrimaryGroupBy.PreGroupObjectFields.Add(new GroupByObjectField("Title", ValueSourceType.Field, "Owner", false));
                currentView.SecondaryGroupBy = new GroupByElement("StartDate");
                currentView.SecondaryGroupBy.PreGroupObjectFields.Add(new GroupByObjectField("Title", ValueSourceType.Field, "StartDate", false));
            }
            currentView.PrimaryGroupBy.IsPreGroupObjectVisible    = true;
            currentView.PrimaryGroupBy.IsPostGroupObjectVisible   = false;
            currentView.SecondaryGroupBy.IsPreGroupObjectVisible  = true;
            currentView.SecondaryGroupBy.IsPostGroupObjectVisible = false;

            currentView.PrimaryGroupBy.PreGroupObjectFields.Add(new GroupByObjectField("DayT", ValueSourceType.Function, GroupByObjectField.SumFunction));
            currentView.PrimaryGroupBy.PreGroupObjectFields.Add(new GroupByObjectField("TotalApproved", ValueSourceType.Function, GroupByObjectField.SumFunction));
            currentView.PrimaryGroupBy.PreGroupObjectFields.Add(new GroupByObjectField("Cost", ValueSourceType.Function, GroupByObjectField.SumFunction));
            currentView.PrimaryGroupBy.PreGroupObjectFields.Add(new GroupByObjectField("ParentBlockId", ValueSourceType.Field, "ParentBlockId"));

            currentView.SecondaryGroupBy.PreGroupObjectFields.Add(new GroupByObjectField("DayT", ValueSourceType.Function, GroupByObjectField.SumFunction));
            currentView.SecondaryGroupBy.PreGroupObjectFields.Add(new GroupByObjectField("TotalApproved", ValueSourceType.Function, GroupByObjectField.SumFunction));
            currentView.SecondaryGroupBy.PreGroupObjectFields.Add(new GroupByObjectField("Cost", ValueSourceType.Function, GroupByObjectField.SumFunction));
            currentView.SecondaryGroupBy.PreGroupObjectFields.Add(new GroupByObjectField("ParentBlockId", ValueSourceType.Field, "ParentBlockId"));

            return(currentView);
        }
Beispiel #6
0
        /// <summary>
        /// Binds the data.
        /// </summary>
        private void BindData()
        {
            if (this.ClassName == TimeTrackingEntry.GetAssignedMetaClass().Name)
            {
                TimeTrackingEntry tte = MetaObjectActivator.CreateInstance <TimeTrackingEntry>(TimeTrackingEntry.GetAssignedMetaClass(), this.ObjectId);

                BindDayHeaders(tte.StartDate);
                BindTTEntry(tte);
                frmView.DataItem = tte;
                frmView.DataBind();

                if (TimeTrackingBlock.CheckUserRight(tte.ParentBlockId, Security.RightWrite))
                {
                    TTBlock.Visible       = false;
                    TTEntry.Visible       = true;
                    ReadOnlyBlock.Visible = false;
                }
                else
                {
                    TTBlock.Visible       = false;
                    TTEntry.Visible       = false;
                    ReadOnlyBlock.Visible = true;
                }
            }
            else if (this.ClassName == TimeTrackingBlock.GetAssignedMetaClass().Name)
            {
                TimeTrackingBlock ttb = MetaObjectActivator.CreateInstance <TimeTrackingBlock>(TimeTrackingBlock.GetAssignedMetaClass(), this.ObjectId);

                frmViewBlock.DataItem = ttb;
                frmViewBlock.DataBind();

                if (TimeTrackingBlock.CheckUserRight(ttb.PrimaryKeyId.Value, Security.RightWrite))
                {
                    TTBlock.Visible       = true;
                    TTEntry.Visible       = false;
                    ReadOnlyBlock.Visible = false;
                }
                else
                {
                    TTBlock.Visible       = false;
                    TTEntry.Visible       = false;
                    ReadOnlyBlock.Visible = true;
                }
            }
            else
            {
                TTBlock.Visible       = false;
                TTEntry.Visible       = false;
                ReadOnlyBlock.Visible = true;
            }
        }
Beispiel #7
0
        /// <summary>
        /// Recalculates the project and objects TotalMinutes and TotalApproved.
        /// </summary>
        /// <param name="block">The block.</param>
        private static void RecalculateProjectAndObjects(TimeTrackingBlock block)
        {
            int projectId = GetProjectIdByTimeTrackingBlock(block);

            if (projectId > 0)
            {
                TimeTrackingEntry[] entryList = TimeTrackingEntry.List(
                    FilterElement.EqualElement("ParentBlockId", block.PrimaryKeyId.Value),
                    FilterElement.IsNotNullElement("ObjectId"),
                    FilterElement.IsNotNullElement("ObjectTypeId"));
                foreach (TimeTrackingEntry entry in entryList)
                {
                    DbTimeTracking.RecalculateObject((int)entry.Properties["ObjectId"].Value, (int)entry.Properties["ObjectTypeId"].Value, block.ProjectId.Value);
                }

                DbTimeTracking.RecalculateProject(projectId);
            }
        }
Beispiel #8
0
        public void Invoke(object Sender, object Element)
        {
            if (Element is CommandParameters)
            {
                CommandParameters cp    = (CommandParameters)Element;
                string[]          elems = MetaGridServer.GetCheckedCollection(((CommandManager)Sender).Page, cp.CommandArguments["GridId"]);

                DateTime   weekStart = CHelper.GetRealWeekStartByDate(DateTime.Now).Date;
                List <int> entryIds  = new List <int>();

                foreach (string elem in elems)
                {
                    //int id = Convert.ToInt32(elem, CultureInfo.InvariantCulture);
                    string type = elem.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries)[1];
                    if (type == MetaViewGroupUtil.keyValueNotDefined)
                    {
                        continue;
                    }

                    int id = Convert.ToInt32(elem.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries)[0], CultureInfo.InvariantCulture);


                    if (type == TimeTrackingEntry.GetAssignedMetaClass().Name)
                    {
                        //if clone current week then abort
                        TimeTrackingEntry tte = MetaObjectActivator.CreateInstance <TimeTrackingEntry>(TimeTrackingEntry.GetAssignedMetaClass(), id);
                        if (weekStart == tte.StartDate)
                        {
                            throw new ArgumentException(CHelper.GetResFileString("{IbnFramework.TimeTracking:_mc_UnableToCloneMsg}"));
                        }

                        entryIds.Add(id);
                    }
                }

                if (entryIds.Count > 0)
                {
                    TimeTrackingManager.AddEntries(weekStart, Mediachase.IBN.Business.Security.CurrentUser.UserID, entryIds);
                }
            }
        }
Beispiel #9
0
        /// <summary>
        /// Handles the Click event of the btnSaveEntry control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnSaveEntry_Click(object sender, EventArgs e)
        {
            double            maxMinutes = (double)(24 * 60);
            TimeTrackingEntry tte        = MetaObjectActivator.CreateInstance <TimeTrackingEntry>(TimeTrackingEntry.GetAssignedMetaClass(), this.ObjectId);

            tte.Day1 = Math.Min((new TimeSpan(Day1Time.Value.Ticks)).TotalMinutes, maxMinutes);
            tte.Day2 = Math.Min((new TimeSpan(Day2Time.Value.Ticks)).TotalMinutes, maxMinutes);
            tte.Day3 = Math.Min((new TimeSpan(Day3Time.Value.Ticks)).TotalMinutes, maxMinutes);
            tte.Day4 = Math.Min((new TimeSpan(Day4Time.Value.Ticks)).TotalMinutes, maxMinutes);
            tte.Day5 = Math.Min((new TimeSpan(Day5Time.Value.Ticks)).TotalMinutes, maxMinutes);
            tte.Day6 = Math.Min((new TimeSpan(Day6Time.Value.Ticks)).TotalMinutes, maxMinutes);
            tte.Day7 = Math.Min((new TimeSpan(Day7Time.Value.Ticks)).TotalMinutes, maxMinutes);

            ProcessCollection(this.frmView.Controls, tte);

            tte.Save();

            CommandParameters cp = new CommandParameters("MC_TimeTracking_EditGridFrame");

            Mediachase.Ibn.Web.UI.WebControls.CommandHandler.RegisterCloseOpenedFrameScript(this.Page, cp.ToString());
        }
Beispiel #10
0
 public override bool CheckVisibility(object dataItem)
 {
     if (dataItem is MetaClass)
     {
         //hide list templates and timetracking classes (not entity objects)
         MetaClass mc = (MetaClass)dataItem;
         if (ListManager.MetaClassIsList(mc))
         {
             ListInfo li = ListManager.GetListInfoByMetaClassName(mc.Name);
             if (li != null && li.IsTemplate)
             {
                 return(false);
             }
         }
         else if (mc.Name == TimeTrackingEntry.GetAssignedMetaClass().Name ||
                  mc.Name == TimeTrackingBlock.GetAssignedMetaClass().Name ||
                  mc.Name == TimeTrackingBlockType.GetAssignedMetaClass().Name ||
                  mc.Name == TimeTrackingBlockTypeInstance.GetAssignedMetaClass().Name)
         {
             return(false);
         }
     }
     return(base.CheckVisibility(dataItem));
 }
Beispiel #11
0
        public static void RegisterFinances(TimeTrackingBlock block, string rowId, DateTime regDate)
        {
            if (!Configuration.TimeTrackingModule)
            {
                throw new Mediachase.Ibn.LicenseRestrictionException();
            }

            if ((bool)block.Properties["AreFinancesRegistered"].Value)
            {
                throw new NotSupportedException("Finances are already registered.");
            }

            if (!TimeTrackingBlock.CheckUserRight(block, TimeTrackingManager.Right_RegFinances))
            {
                throw new Mediachase.Ibn.AccessDeniedException();
            }

            ///  TimeTrackingEntryId, UserId, ObjectTypeId, ObjectId, Title,
            ///  Day1, Day2, Day3, Day4, Day5, Day6, Day7, Total, TotalApproved, Rate, Cost
            DataTable dt = GetListTimeTrackingItemsForFinances_DataTable(block.BlockTypeInstanceId, block.StartDate, block.OwnerId);

            using (DbTransaction tran = DbTransaction.Begin())
            {
                // O.R. [2008-07-29]: We don't need to check the "Write" right for Entry and Block
                using (SkipSecurityCheckScope scope = Mediachase.Ibn.Data.Services.Security.SkipSecurityCheck())
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        // O.R. [2008-07-28]: Rate and TotalApproved may contain null values, so we need do assign them
                        TimeTrackingEntry entry = MetaObjectActivator.CreateInstance <TimeTrackingEntry>(TimeTrackingEntry.GetAssignedMetaClass(), (int)row["TimeTrackingEntryId"]);
                        entry.Properties["Rate"].Value          = row["Rate"];
                        entry.Properties["TotalApproved"].Value = row["TotalApproved"];
                        entry.Save();

                        double cost = (double)row["Cost"];
                        if (cost == 0d)
                        {
                            continue;
                        }

                        // O.R. [2008-07-24] Now we use ProjectId

                        /*					ObjectTypes objectType = ObjectTypes.Timesheet;
                         *                                      int objectId = (int)row["TimeTrackingEntryId"];
                         */
                        ObjectTypes objectType = ObjectTypes.Project;
                        int         objectId   = block.ProjectId.Value;

                        if (row["ObjectTypeId"] != DBNull.Value && row["ObjectId"] != DBNull.Value)
                        {
                            objectType = (ObjectTypes)row["ObjectTypeId"];
                            objectId   = (int)row["ObjectId"];
                        }

                        // row["TotalApproved"] alwas has not null value
                        ActualFinances.Create(objectId, objectType, regDate, rowId, cost, row["Title"].ToString(), block.PrimaryKeyId.Value, (double)row["TotalApproved"], (int)block.OwnerId);
                    }

                    block.Properties["AreFinancesRegistered"].Value = true;
                    block.Save();
                }

                // Recalculate TotalMinutes and TotalApproved
                RecalculateProjectAndObjects(block);

                tran.Commit();
            }
        }
Beispiel #12
0
        public static void Main(string[] args)
        {
            var authorizationSettings = new AuthorizationSettings
            {
                ApplicationKey = "<You Application Key Here>",
                ClientKey      = "<PowerOffice Go Client Key Here>",
                TokenStore     = new BasicTokenStore(@"my.tokenstore")
            };

            // Initialize the PowerOffice Go API and request authorization
            var api = new Go(authorizationSettings);

            //Get and print out all hour types available on the Client
            Console.WriteLine("Hour types:");
            var hourTypes = api.TimeTracking.HourType.Get().ToArray();

            foreach (var hourType in hourTypes)
            {
                Console.WriteLine($"{hourType.Description} | PayItemCode: {hourType.PayItemCode} | IsActive: {hourType.IsActive}");
            }

            Console.WriteLine();

            //Get and print all Activities available on the Client.
            Console.WriteLine("Activities:");
            var activities = api.TimeTracking.Activity.Get().ToArray();

            foreach (var activity in activities)
            {
                Console.WriteLine($"{activity.Name} ({activity.Code}) | Type: {activity.ActivityType} | IsActive: {activity.IsActive}");
            }

            Console.WriteLine();

            //Query time tracking entries this month
            Console.WriteLine("Time tracking entries:");
            var currentDate         = DateTime.Today;
            var monthStart          = new DateTime(currentDate.Year, currentDate.Month, 1);
            var timeTrackingEntries = api.TimeTracking.TimeTrackingEntry.Get().Where(t => t.Date >= monthStart).OrderBy(t => t.Date).ToArray();

            foreach (var timeTrackingEntry in timeTrackingEntries)
            {
                Console.WriteLine($"{timeTrackingEntry.EmployeeCode} - {timeTrackingEntry.ActivityCode} - {timeTrackingEntry.Date} - {timeTrackingEntry.Hours}");
            }

            Console.WriteLine();

            //Get entry for a given employee, project, activity and hour type, or create new with the same dimensions
            var date          = new DateTime(2017, 7, 3);
            var employeeCode  = 1;
            var activityCode  = "802";
            var projectCode   = "2";
            var hourTypeToUse = "Overtid 100 %";
            var numberOfHours = 12;


            var timeTrackingEntryToEdit =
                timeTrackingEntries.FirstOrDefault(t => t.Date == date && t.EmployeeCode == employeeCode && t.ActivityCode == activityCode && t.ProjectCode == projectCode && t.HourType == hourTypeToUse);

            if (timeTrackingEntryToEdit != null)
            {
                timeTrackingEntryToEdit.Hours  += numberOfHours;
                timeTrackingEntryToEdit.Comment = "A comment from edit";
            }
            else
            {
                timeTrackingEntryToEdit = new TimeTrackingEntry()
                {
                    ActivityCode = activityCode,
                    Date         = date,
                    Comment      = "A comment",
                    Hours        = numberOfHours,
                    EmployeeCode = employeeCode,
                    ProjectCode  = projectCode,
                    HourType     = hourTypeToUse
                };
            }

            //Save the time tracking entry
            api.TimeTracking.TimeTrackingEntry.Save(timeTrackingEntryToEdit);

            //Query again and print
            Console.WriteLine("Time tracking entries:");
            timeTrackingEntries = api.TimeTracking.TimeTrackingEntry.Get().Where(t => t.Date >= monthStart).OrderBy(t => t.Date).ToArray();
            foreach (var timeTrackingEntry in timeTrackingEntries)
            {
                Console.WriteLine($"{timeTrackingEntry.EmployeeCode} - {timeTrackingEntry.ActivityCode} - {timeTrackingEntry.Date} - {timeTrackingEntry.Hours}");
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Beispiel #13
0
        public void Invoke(object Sender, object Element)
        {
            if (Element is CommandParameters)
            {
                CommandParameters cp = (CommandParameters)Element;

                string[] elems = null;
                if (cp.CommandArguments.ContainsKey("GridId"))
                {
                    elems = MetaGridServer.GetCheckedCollection(((CommandManager)Sender).Page, cp.CommandArguments["GridId"]);
                }

                List <int> ttbIds = new List <int>();

                //fix by DV: 2008-05-14
                //Esli vyzyvaetsa s grida (iconka v otklonennih listah), to primitiv v gride ustanovit etot flag
                //i togda ID budet bratsa iz parametrov, v protivnom sluchae ID - beretsa iz checkboxes
                if (!cp.CommandArguments.ContainsKey("callFromGrid"))
                {
                    foreach (string elem in elems)
                    {
                        string type = MetaViewGroupUtil.GetMetaTypeFromUniqueKey(elem);                        // elem.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries)[1];
                        if (type == MetaViewGroupUtil.keyValueNotDefined)
                        {
                            continue;
                        }

                        int id = Convert.ToInt32(MetaViewGroupUtil.GetIdFromUniqueKey(elem), CultureInfo.InvariantCulture);                         //Convert.ToInt32(elem.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries)[0], CultureInfo.InvariantCulture);


                        if (type == TimeTrackingEntry.GetAssignedMetaClass().Name)
                        {
                            //TimeTrackingEntry tte = MetaObjectActivator.CreateInstance<TimeTrackingEntry>(TimeTrackingEntry.GetAssignedMetaClass(), id);

                            //if (!ttbIds.Contains(tte.ParentBlockId))
                            //    ttbIds.Add(tte.ParentBlockId);
                        }
                        else
                        {
                            if (!ttbIds.Contains(id))
                            {
                                ttbIds.Add(id);
                            }
                        }
                    }
                }
                else
                {
                    ttbIds.Add(Convert.ToInt32(MetaViewGroupUtil.GetIdFromUniqueKey(cp.CommandArguments["primaryKeyId"]), CultureInfo.InvariantCulture));
                }

                using (TransactionScope tran = DataContext.Current.BeginTransaction())
                {
                    foreach (int ttbId in ttbIds)
                    {
                        TimeTrackingBlock ttb = MetaObjectActivator.CreateInstance <TimeTrackingBlock>(TimeTrackingBlock.GetAssignedMetaClass(), ttbId);

                        StateMachineService sms = ((BusinessObject)ttb).GetService <StateMachineService>();

                        // process only initial state
                        if (sms.StateMachine.GetStateIndex(sms.CurrentState.Name) == 0)
                        {
                            StateTransition[] availableTransitions = sms.GetNextAvailableTransitions(true);
                            if (availableTransitions.Length > 0)
                            {
                                sms.MakeTransition(availableTransitions[0].Uid);
                                ttb.Save();
                            }
                        }
                    }
                    tran.Commit();
                }
            }
        }
Beispiel #14
0
        public void Invoke(object Sender, object Element)
        {
            if (Element is CommandParameters)
            {
                // we'll use this list to collect unique block id's taken from deleted entries
                // at the end we'll delete empty blocks
                ArrayList blocks = new ArrayList();

                int deletedItems                = 0;
                CommandParameters cp            = (CommandParameters)Element;
                string[]          elemsToDelete = MetaGridServer.GetCheckedCollection(((CommandManager)Sender).Page, cp.CommandArguments["GridId"]);
                using (TransactionScope tran = DataContext.Current.BeginTransaction())
                {
                    //1. All entries
                    foreach (string elem in elemsToDelete)
                    {
                        string type = elem.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries)[1];
                        if (type == MetaViewGroupUtil.keyValueNotDefined)
                        {
                            deletedItems++;
                            continue;
                        }

                        int id = Convert.ToInt32(elem.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries)[0]);

                        //int id = int.Parse(elem);
                        if (type != TimeTrackingEntry.GetAssignedMetaClass().Name)
                        {
                            continue;
                        }

                        TimeTrackingEntry tte = MetaObjectActivator.CreateInstance <TimeTrackingEntry>(TimeTrackingEntry.GetAssignedMetaClass(), id);
                        if (TimeTrackingManager.DeleteEntry(tte))
                        {
                            deletedItems++;

                            if (!blocks.Contains(tte.ParentBlockId))
                            {
                                blocks.Add(tte.ParentBlockId);
                            }
                        }
                    }
                    //2. All blocks
                    foreach (string elem in elemsToDelete)
                    {
                        string type = elem.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries)[1];
                        if (type == MetaViewGroupUtil.keyValueNotDefined)
                        {
                            continue;
                        }

                        int id = Convert.ToInt32(elem.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries)[0]);

                        //if (id >= 0)
                        //    continue;
                        //id = -id;
                        if (type != TimeTrackingBlock.GetAssignedMetaClass().Name)
                        {
                            continue;
                        }

                        TimeTrackingBlock ttb = MetaObjectActivator.CreateInstance <TimeTrackingBlock>(TimeTrackingBlock.GetAssignedMetaClass(), id);
                        if (Mediachase.Ibn.Data.Services.Security.CanDelete(ttb))
                        {
                            ttb.Delete();
                            deletedItems++;

                            if (blocks.Contains(ttb.PrimaryKeyId))
                            {
                                blocks.Remove(ttb.PrimaryKeyId);
                            }
                        }
                    }

                    // delete empty blocks
                    using (SkipSecurityCheckScope scope = Mediachase.Ibn.Data.Services.Security.SkipSecurityCheck())
                    {
                        foreach (PrimaryKeyId blockId in blocks)
                        {
                            TimeTrackingEntry[] entries = TimeTrackingEntry.List(FilterElement.EqualElement("ParentBlockId", blockId));
                            if (entries.Length == 0)
                            {
                                TimeTrackingBlock ttb = MetaObjectActivator.CreateInstance <TimeTrackingBlock>(TimeTrackingBlock.GetAssignedMetaClass(), blockId);
                                ttb.Delete();
                            }
                        }
                    }

                    tran.Commit();
                }

                CommandManager cm = Sender as CommandManager;
                if (cm != null)
                {
                    if (deletedItems != elemsToDelete.Length)
                    {
                        cm.InfoMessage = CHelper.GetResFileString("{IbnFramework.Common:NotAllSelectedItemsWereProcessed}");
                    }
                    //    cm.InfoMessage = CHelper.GetResFileString("{IbnFramework.Common:AllSelectedItemsWereProcessed}");
                }

                //CHelper.RequireBindGrid();
                CHelper.AddToContext("NeedToClearSelector", "true");
            }
        }