Beispiel #1
0
        private void InsertTestInternal(ClientSettings settings, int slotID, WorkUnit workUnit, Protein protein, Action <IList <WorkUnitRow> > verifyAction)
        {
            _repository.Initialize(_testScratchFile);

            var slotModel = new SlotModel(new NullClient {
                Settings = settings
            })
            {
                SlotID = slotID
            };
            var workUnitModel = new WorkUnitModel(slotModel, workUnit);

            workUnitModel.CurrentProtein = protein;

            _repository.Insert(workUnitModel);

            var rows = _repository.Fetch(WorkUnitQuery.SelectAll, BonusCalculation.None);

            verifyAction(rows);

            // test code to ensure this unit is NOT written again
            _repository.Insert(workUnitModel);
            // verify
            rows = _repository.Fetch(WorkUnitQuery.SelectAll, BonusCalculation.None);
            Assert.AreEqual(1, rows.Count);
        }
Beispiel #2
0
        private static WorkUnit BuildWorkUnit4()
        {
            var workUnit = new WorkUnit();

            workUnit.ProjectID    = 6903;
            workUnit.ProjectRun   = 2;
            workUnit.ProjectClone = 3;
            workUnit.ProjectGen   = 4;
            workUnit.FoldingID    = "harlam357";
            workUnit.Team         = 32;
            workUnit.CoreVersion  = 2.27f;
            workUnit.UnitResult   = WorkUnitResult.FinishedUnit;

            // These values can be either Utc or Unspecified. Setting SQLite's DateTimeKind
            // connection string option to Utc will force SQLite to handle all DateTime
            // values as Utc regardless of the DateTimeKind specified in the value.
            workUnit.Assigned = new DateTime(2012, 1, 2);
            workUnit.Finished = new DateTime(2012, 1, 5);

            // these values effect the value reported when WorkUnitModel.GetRawTime() is called
            //workUnit.FramesObserved = 1;
            var frameDataDictionary = new Dictionary <int, LogLineFrameData>()
                                      .With(new LogLineFrameData {
                ID = 100, Duration = TimeSpan.FromMinutes(10)
            });

            workUnit.Frames = frameDataDictionary;
            return(workUnit);
        }
        public async Task <ActionResult> EditEditWork(int id, int workid, DailyWorkUnitData dailyWorkUnitData)
        {
            if (Session["LoginUserID"] == null)
            {
                return(RedirectToAction("Login", "Account"));
            }

            if (ModelState.IsValid)
            {
                //                db.Entry(materialBuyData).State = EntityState.Modified;
                DailyWork dailyWork = db.DailyWorks.FirstOrDefault(m => m.ID == dailyWorkUnitData.DailyWork.ID);
                WorkUnit  workUnit  = await db.WorkUnits.FindAsync(workid);

                if (workUnit.WorkNameVn != dailyWorkUnitData.WorkUnit.WorkNameVn)
                {
                    workUnit.Translate = false;
                }
                if (workUnit.NoteVn != dailyWorkUnitData.WorkUnit.NoteVn)
                {
                    workUnit.Translate = false;
                }
                workUnit.StartDate  = dailyWorkUnitData.WorkUnit.StartDate;
                workUnit.EndDate    = dailyWorkUnitData.WorkUnit.EndDate;
                workUnit.Complete   = dailyWorkUnitData.WorkUnit.Complete;
                workUnit.WorkNameVn = dailyWorkUnitData.WorkUnit.WorkNameVn;
                workUnit.NoteVn     = dailyWorkUnitData.WorkUnit.NoteVn;

                await db.SaveChangesAsync();

                return(RedirectToAction("EditAddWork", new { id = dailyWorkUnitData.DailyWork.ID }));
            }
            return(View(dailyWorkUnitData));
        }
Beispiel #4
0
        private static void PopulateWorkUnitFromFahClientData(WorkUnit workUnit, Unit unit, Options options)
        {
            Debug.Assert(workUnit != null);
            Debug.Assert(unit != null);
            Debug.Assert(options != null);

            workUnit.QueueIndex = unit.ID.GetValueOrDefault();

            workUnit.Assigned = unit.AssignedDateTime.GetValueOrDefault();

            workUnit.Timeout = unit.TimeoutDateTime.GetValueOrDefault();

            /* Project (R/C/G) */
            workUnit.ProjectID    = unit.Project.GetValueOrDefault();
            workUnit.ProjectRun   = unit.Run.GetValueOrDefault();
            workUnit.ProjectClone = unit.Clone.GetValueOrDefault();
            workUnit.ProjectGen   = unit.Gen.GetValueOrDefault();

            /* FoldingID and Team from Queue Entry */
            workUnit.FoldingID = options[Options.User] ?? Unknown.Value;
            workUnit.Team      = ToNullableInt32(options[Options.Team]).GetValueOrDefault();

            /* Core ID */
            workUnit.CoreID = unit.Core.Replace("0x", String.Empty).ToUpperInvariant();
        }
Beispiel #5
0
        public void FahClient_UpdateBenchmarkFrameTimes_DoesNotUpdateBenchmarksWhenNoFramesAreComplete()
        {
            // Arrange
            var benchmarkService = new ProteinBenchmarkService(new ProteinBenchmarkDataContainer());
            var fahClient        = new FahClient(null, new InMemoryPreferencesProvider(), benchmarkService, null, null);

            var workUnit = new WorkUnit();

            workUnit.ProjectID    = 12345;
            workUnit.ProjectRun   = 6;
            workUnit.ProjectClone = 7;
            workUnit.ProjectGen   = 8;
            workUnit.Assigned     = DateTime.UtcNow;
            var settings = new ClientSettings {
                Name = "Foo", Server = "Bar", Port = ClientSettings.DefaultPort
            };
            var workUnitModel = new WorkUnitModel(new SlotModel(new NullClient {
                Settings = settings
            }), workUnit);
            var newWorkUnitModel = new WorkUnitModel(workUnitModel.SlotModel, workUnit.Copy());

            // Act
            fahClient.UpdateBenchmarkFrameTimes(workUnitModel, newWorkUnitModel);

            // Assert
            Assert.IsNull(benchmarkService.GetBenchmark(newWorkUnitModel.SlotModel.SlotIdentifier, newWorkUnitModel.BenchmarkIdentifier));
        }
Beispiel #6
0
        int IComparer.Compare(object a, object b)
        {
            WorkUnit wwuA = a as WorkUnit;
            WorkUnit wwuB = b as WorkUnit;

            return(wwuA.PhysicalPath.CompareTo(wwuB.PhysicalPath));
        }
Beispiel #7
0
 public WorkUnitPanelItem(WorkUnitsPanel ownerControl, WorkUnit workUnit)
 {
     this.ownerControl              = ownerControl;
     this.workUnit                  = workUnit;
     this.WorkUnit.PropertyChanged += this.WorkUnit_PropertyChanged;
     this.NeedToUpdateSize          = true;
 }
Beispiel #8
0
        public ReadOnlyCollection <IJob> PendingJobs(WorkUnit unit)
        {
            List <IJob> results = new List <IJob>();

            if (unit.GetType() == typeof(CPUWorkUnit))
            {
                foreach (CPUCore core in cores)
                {
                    if (core.WorkUnit == unit)
                    {
                        foreach (WorkerThread wt in core.WorkerThreads)
                        {
                            foreach (IJob job in wt.JobQueue)
                            {
                                results.Add(job);
                            }
                        }

                        break;
                    }
                }
            }

            /** FIXME: no code for other WU types yet **/

            return(new ReadOnlyCollection <IJob>(results));
        }
    public static WorkUnit add_preds(ref WorkUnit current, CircuitOp gate)
    {
        int[] predecessors = state_ball(current.target, gate.qubits);
        switch (gate.op)
        {
        case Op.H:
            current.dep_done_0 = false; current.dep_done_1 = false;
            current.dep_done_2 = true; current.dep_done_3 = true;

            current.dep_target_0 = predecessors[0]; current.dep_target_1 = predecessors[1];
            current.dep_target_2 = 0; current.dep_target_3 = 0;
            break;

        case Op.CNOT:
            current.dep_done_0 = false; current.dep_done_1 = false;
            current.dep_done_2 = false; current.dep_done_3 = false;

            current.dep_target_0 = predecessors[0]; current.dep_target_1 = predecessors[1];
            current.dep_target_2 = predecessors[0]; current.dep_target_3 = predecessors[1];
            break;

        default:
            Console.WriteLine("UNKNOWN OPERATION!");
            break;
        }
        return(current);
    }
        public async Task GivenRepoWhenDeleteCalledThenItemIsRemoved()
        {
            var id = string.Empty;

            using (var ctx = new FoodContext())
            {
                var description = TestHelper.GetNewFoodDescription();
                id = description.Id;
                ctx.FoodDescriptions.Add(description);
                await ctx.SaveChangesAsync();
            }

            using (var unit = new WorkUnit(Thread.CurrentPrincipal))
            {
                var repo    = new FoodDescriptionRepo();
                var success = await repo.DeleteFoodDescriptionAsync(unit, id);

                Assert.IsTrue(success, "Test failed: operation should have returned true.");
                await unit.CommitAsync();
            }

            using (var ctx = new FoodContext())
            {
                var exists = ctx.FoodDescriptions.Any(f => f.Id == id);
                Assert.IsFalse(exists, "Test failed: item was not deleted.");
            }
        }
        public async Task GivenRepoWhenExistingItemThenItemIsUpdated()
        {
            FoodDescription item;
            DateTimeOffset  date;

            using (var ctx = new FoodContext())
            {
                item = ctx.FoodDescriptions.AsNoTracking().FirstOrDefault();
                date = item.SomeDate;
            }

            using (var unit = new WorkUnit(Thread.CurrentPrincipal))
            {
                var repo = new FoodDescriptionRepo();
                item.SomeDate = date.AddDays(1);
                var success = await repo.UpdateOrAddFoodDescriptionAsync(unit, item);

                Assert.IsNotNull(success, "Test failed: operation should have returned the item.");
                await unit.CommitAsync();
            }

            using (var ctx = new FoodContext())
            {
                var actual = ctx.FoodDescriptions.FirstOrDefault(f => f.Id == item.Id);
                Assert.IsNotNull(actual, "Test failed: unable to obtain the item.");
                Assert.AreNotEqual(date, actual.SomeDate, "Test failed: the date was not updated.");
            }
        }
    public static Complex CalcAmpFlat(CircuitOp[] remaining_circuit, int circuitpos, int inital_state, int target_state)
    {
        int curridx = -1; // number of active elements in the queue.

        WorkUnit[] worklist = new WorkUnit[16];

        CircuitOp current_gate = remaining_circuit[circuitpos - 1];

        // wuDefault(ref worklist[0]); // ref types don't work in Kiwi, fine
        // WorkUnit firstelement = wuDefault();
        worklist[0].target = target_state;
        worklist[0].depth  = circuitpos;
        // add_preds(ref worklist[0], current_gate);


        curridx = 0; // if -1, return.
        WorkUnit current;
        Complex  lasteval;

        // while (curridx > 0) { // valid indices for the work list
        //   Kiwi.Pause();
        //   current = worklist[curridx-1];
        //   current_gate = remaining_circuit[curridx-1];
        //   if (can_evaluate(current)) {
        //     lasteval = evaluate(current, current_gate);
        //     curridx -= 1; // pop off the stack.
        //   } else {
        //     Console.WriteLine("need to addd to the worklist, cant do that yet!");
        //     curridx -= 1;
        //   }
        // }

        Console.WriteLine("RAN OFF THE END OF THE WORKLIST!");
        return(new Complex(0.0, 0.0));
    }
Beispiel #13
0
    /**
     * pieregjistreee levelobjeta padoto darbinju kopeejaa listee
     */
    public void AddWork(WorkUnit workunit)
    {
        workunit.Init();
        worklist.Add(workunit);

        IsThereWorkAvailable();
    }
Beispiel #14
0
 public override void UpdateWorkUnits(DataRow row)
 {
     this.groupValues = this.GetValues(row);
     if (!string.IsNullOrEmpty(base.WorkUnitTextColumn))
     {
         this.workUnitsTextList = (row[base.WorkUnitTextColumn] as IList);
     }
     if (this.groupValues != null && this.groupValues.Count > 0)
     {
         this.dataHandler.DataHandlers.Clear();
         if (string.IsNullOrEmpty(this.CommandParam))
         {
             WorkUnit[] array = new WorkUnit[this.groupValues.Count];
             for (int i = 0; i < this.groupValues.Count; i++)
             {
                 array[i] = new WorkUnit(this.GetDisplayText(i), this.GetDisplayIcon(row), this.groupValues[i]);
             }
             this.dataHandler.DataHandlers.Add(new BulkSaveDataHandler(array.DeepCopy(), this.CommandText));
         }
         else
         {
             for (int j = 0; j < this.groupValues.Count; j++)
             {
                 this.dataHandler.DataHandlers.Add(this.CreateDataHandler(this.CommandText, j, this.GetDisplayIcon(row)));
             }
         }
         this.dataHandler.UpdateWorkUnits();
         foreach (WorkUnit workUnit in this.dataHandler.WorkUnits)
         {
             workUnit.Description = this.ModifiedParametersDescription;
         }
         this.dataHandler.ResetCancel();
     }
 }
        public async Task <ActionResult> EditEditWork(int?id, int workid)
        {
            if (Session["LoginUserID"] == null)
            {
                return(RedirectToAction("Login", "Account"));
            }

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            DailyWork dailyWork = await db.DailyWorks.FindAsync(id);

            if (dailyWork == null)
            {
                return(HttpNotFound());
            }
            WorkUnit workUnit = await db.WorkUnits.FindAsync(workid);

            if (workUnit == null)
            {
                return(HttpNotFound());
            }
            var dailyWorkUnitData = new DailyWorkUnitData();

            dailyWorkUnitData.DailyWork = dailyWork;
            dailyWorkUnitData.WorkUnit  = workUnit;

            ViewBag.WorkUnits = db.WorkUnits.Where(w => w.ProjectID == dailyWork.ProjectID && w.StartDate <= dailyWork.Date &&
                                                   (w.Complete == false || w.EndDate >= dailyWork.Date)).ToList();

            return(View(dailyWorkUnitData));
        }
 static public void wuDefault(ref WorkUnit ret)
 {
     ret.target       = 0; ret.depth = 0;
     ret.dep_done_0   = false; ret.dep_done_1 = false; ret.dep_done_2 = false; ret.dep_done_3 = false;
     ret.dep_target_0 = 0; ret.dep_target_1 = 0; ret.dep_target_2 = 0; ret.dep_target_3 = 0;
     ret.dep_amp_0    = zero; ret.dep_amp_1 = zero; ret.dep_amp_2 = zero; ret.dep_amp_3 = zero;
 }
 protected override void afterPopulateProps()
 {
     afterPropertySetPopulateProps();
     WorkUnit.SetOnPropChange( OnWorkUnitPropChange );
     ApplyToAllWorkUnits.SetOnPropChange( OnApplyToAllWorkUnitsPropChange );
     Role.SetOnPropChange( OnRolePropChange );
     ApplyToAllRoles.SetOnPropChange( OnApplyToAllRolesPropChange );
 }
Beispiel #18
0
        public ActionResult DeleteConfirmed(int id)
        {
            WorkUnit workUnit = db.WorkUnits.Find(id);

            db.WorkUnits.Remove(workUnit);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Beispiel #19
0
 private static ICollection <TimeSpan> GetFrameTimes(WorkUnit workUnit, int nextFrame, int count)
 {
     return(Enumerable.Range(nextFrame, count)
            .Select(workUnit.GetFrame)
            .Where(f => f != null)
            .Select(f => f.Duration)
            .ToList());
 }
 private void cboReworkUnits_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (cboReworkUnits.SelectedItem != null)
     {
         WorkUnit workUnit = cboReworkUnits.SelectedItem as WorkUnit;
         GetCurrentLoadingSheet(pwo.T102LeafID, workUnit.T107LeafID);
     }
 }
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            WorkUnit workUnit = await db.WorkUnits.FindAsync(id);

            db.WorkUnits.Remove(workUnit);
            await db.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
Beispiel #22
0
 internal CPUCore(WorkUnit wu, int concurrencyMultiplier)
 {
     this.workUnit = wu;
     for (int i = 0; i < concurrencyMultiplier; ++i)
     {
         this.workerThreads.Add(
             new WorkerThread(workUnit as CPUWorkUnit));
     }
 }
Beispiel #23
0
        // mbr - 25-09-2007 - moved to provider.
//		/// <summary>
//		/// Gets or sets the deleteExtendedPropertyworkunittype
//		/// </summary>
//		public Type DeleteAllExtendedPropertyWorkUnitType
//		{
//			get
//			{
//				return _deleteAllExtendedPropertyWorkUnitType;
//			}
//			set
//			{
//				// check to see if the value has changed...
//				if(value != _deleteAllExtendedPropertyWorkUnitType)
//				{
//					// set the value...
//					_deleteAllExtendedPropertyWorkUnitType = value;
//				}
//			}
//		}
//
//		/// <summary>
//		/// Gets or sets the updateExtendedPropertyworkunittype
//		/// </summary>
//		public Type UpdateExtendedPropertyWorkUnitType
//		{
//			get
//			{
//				return _updateExtendedPropertyWorkUnitType;
//			}
//			set
//			{
//				// check to see if the value has changed...
//				if(value != _updateExtendedPropertyWorkUnitType)
//				{
//					// set the value...
//					_updateExtendedPropertyWorkUnitType = value;
//				}
//			}
//		}
//
//		/// <summary>
//		/// Gets the insertExtendedPropertyworkunittype.
//		/// </summary>
//		public Type InsertExtendedPropertyWorkUnitType
//		{
//			get
//			{
//				return _insertExtendedPropertyWorkUnitType;
//			}
//			set
//			{
//				if(_insertExtendedPropertyWorkUnitType != value)
//					_insertExtendedPropertyWorkUnitType = value;
//			}
//		}

        /// <summary>
        /// Creates an insert work unit for the entity.
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="storage"></param>
        /// <returns></returns>
        protected internal override IWorkUnit CreateInsertWorkUnit(object entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            // check...
            if (InsertWorkUnitType == null)
            {
                throw new ArgumentNullException("InsertWorkUnitType");
            }
            if (EntityType == null)
            {
                throw new ArgumentNullException("EntityType");
            }
            if (InsertWorkUnitType == null)
            {
                throw new ArgumentNullException("InsertWorkUnitType");
            }
            if (Storage.IsNew(entity) == false)
            {
                throw new InvalidOperationException("Entity is not new.");
            }

            // mbr - 13-10-2005 - if the entity type is using partitioning, give the partition an opportunity to set the partition ID prior to insert...
            //if(this.EntityType.SupportsPartitioning)
            //{
            //    // get the strategy...
            //    PartitioningStrategy strategy = this.EntityType.PartitioningStrategy;
            //    if(strategy == null)
            //        throw new InvalidOperationException("strategy is null.");

            //    // apply...
            //    strategy.BeforeInsert(this.EntityType, entity);
            //}

            // get all of the fields...
            EntityField[] fields = GetModifiedFields(entity);
            object[]      values = this.Storage.GetValues(entity, fields, FetchFlags.KeepEncrypted);

            // create...
            try
            {
                // mbr - 13-10-2005 - added null check...
                WorkUnit unit = (WorkUnit)Activator.CreateInstance(this.InsertWorkUnitType, new object[] { this.EntityType, entity, fields, values });
                if (unit == null)
                {
                    throw new InvalidOperationException("unit is null.");
                }
                return(unit);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(string.Format(Cultures.Exceptions, "Failed to instantiate an instance of '{0}'.", this.InsertWorkUnitType), ex);
            }
        }
Beispiel #24
0
        public void Create(CreateWorkUnitDto dto)
        {
            var workUnit = new WorkUnit
            {
                Title = dto.Title
            };

            _workUnitRepository.Insert(workUnit);
        }
Beispiel #25
0
 public Boolean Add(WorkUnit record)
 {
     if (record == null)
     {
         return(false);
     }
     WorkUnits.Add(record);
     return(SaveChanges() == 1);
 }
 private void OnCancelClick()
 {
     if (WorkUnit != null)
     {
         if (WorkUnit.StatusOfWork == Status.Started || WorkUnit.StatusOfWork == Status.Running)
         {
             WorkUnit.CancelWork();
         }
     }
 }
 public override void setWildCardValues()
 {
     Dispense.Checked       = CswEnumTristate.True;
     Dispose.Checked        = CswEnumTristate.True;
     Request.Checked        = CswEnumTristate.True;
     Undispose.Checked      = CswEnumTristate.True;
     WorkUnit.RelatedNodeId = null;
     WorkUnit.RefreshNodeName();
     WorkUnit.SyncGestalt();
 }
Beispiel #28
0
 public ActionResult Edit([Bind(Include = "Id,CreateTime,Name,UpdateTime")] WorkUnit workUnit)
 {
     if (ModelState.IsValid)
     {
         db.Entry(workUnit).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(workUnit));
 }
        private void grdRouters_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(WorkUnit)))
            {
                WorkUnit source = (WorkUnit)e.Data.GetData(typeof(WorkUnit));

                // 获取鼠标拖放位置
                point = grdRouters.PointToClient(new Point(e.X, e.Y));
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hi = grdvRouters.CalcHitInfo(point);

                if (hi.RowHandle >= 0 && hi.RowHandle < routers.Count)
                {
                    if (hi.Column == grdclmnCurrWorkUnit)
                    {
                        if (routers[hi.RowHandle].NextWorkUnit.T107LeafID == source.T107LeafID)
                        {
                            XtraMessageBox.Show("当前工位和下一工位不能是相同的工位!",
                                                "系统信息",
                                                MessageBoxButtons.OK,
                                                MessageBoxIcon.Error);
                        }
                        else
                        {
                            routers[hi.RowHandle].CurrWorkUnit = source.Clone();
                            ArrangeReworkRouters();
                        }
                    }
                    else if (hi.Column == grdclmnPrevWorkUnit)
                    {
                        if (routers[hi.RowHandle].CurrWorkUnit.T107LeafID == source.T107LeafID)
                        {
                            XtraMessageBox.Show("当前工位和下一工位不能是相同的工位!",
                                                "系统信息",
                                                MessageBoxButtons.OK,
                                                MessageBoxIcon.Error);
                        }
                        else
                        {
                            routers[hi.RowHandle].NextWorkUnit = source.Clone();
                            ArrangeReworkRouters();
                        }
                    }
                }
                else
                {
                    GUIReworkRouter router = new GUIReworkRouter()
                    {
                        CurrWorkUnit = source.Clone()
                    };
                    routers.Add(router);
                    grdvRouters.FocusedRowHandle = routers.Count - 1;
                    ArrangeReworkRouters();
                }
            }
        }
        public async Task <ActionResult> DeleteWorkUnit(int id, int Workid)
        {
            WorkUnit workUnit = await db.WorkUnits.FindAsync(Workid);

            db.WorkUnits.Remove(workUnit);

            //PreDeleteUnit(id, paymentid);
            await db.SaveChangesAsync();

            return(RedirectToAction("EditAddWork", new { id = id }));
        }
Beispiel #31
0
    /**
     * izveido buuvdarbu (sho netaisa prefabam caur Unity inspektoru, jo shis ir iislaiciigi pieejams darbs)
     */
    public void CreateAndAddConstructionJob(Room block, Gadget gadget, WorkUnit.WorkUnitTypes workType)
    {
        WorkUnit constructionJob = new WorkUnit();

            constructionJob.parentGameobject = block.gameObject;
            constructionJob.parentGadget = gadget;//null, ja shis nav gadzheta darbs

        constructionJob.WorkUnitTypeNumber = workType;
        constructionJob.setOn(true);
        AddWork(constructionJob);
    }
Beispiel #32
0
        public ActionResult Create([Bind(Include = "Id,CreateTime,Name,UpdateTime")] WorkUnit workUnit)
        {
            if (ModelState.IsValid)
            {
                db.WorkUnits.Add(workUnit);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(workUnit));
        }
        public void GivenWorkUnitWhenNotCommittedThenDatabaseShouldRemainTheSame()
        {
            var id = string.Empty;
            var date = DateTime.Now;
            using (var unit = new WorkUnit(Thread.CurrentPrincipal))
            {
                var firstItem = unit.Collection<FoodDescription>().FirstOrDefault();
                firstItem.SomeDate = date;
                id = firstItem.Id;
            }

            using (var ctx = new FoodContext())
            {
                var actual = ctx.FoodDescriptions.Find(id);
                if (actual == null)
                {
                    Assert.Fail("Item was not found.");
                }
                Assert.IsFalse(actual.SomeDate == date, "Test failed: date should not have been updated.");
            }
        }
        public void SendRegistrationToServer(Task task, TimeSpan duration, string comment)
        {
            DateTime now = DateTime.Now;
            DateTime start = now.Subtract(duration);
            DateTime end = now;

            var workunit = new WorkUnit
                               {
                Description = comment,
                Duration = duration,
                TaskID = task.ID,
                GUID = new Guid(),
                EmployeeInitials = App.IdentityViewModel.User,
                EndDateTime = end,
                StartDateTime = start
            };

            var workUnits = new ObservableCollection<WorkUnit> {workunit};

            var prjClient = new ProjectManagementServiceClient();
            prjClient.Endpoint.Address = new System.ServiceModel.EndpointAddress(prjClient.Endpoint.Address.ToString().Replace("app.timelog.dk/local", App.IdentityViewModel.HostAddr));
            prjClient.InsertWorkCompleted += PrjClientInsertWorkCompleted;
            prjClient.InsertWorkAsync(new InsertWorkRequest(workUnits, 99, App.IdentityViewModel.ProjectToken));
        }
        /// <summary>
        /// Inserts a new work unit
        /// </summary>
        /// <param name="date">Date of work</param>
        /// <param name="hours">Number of hours</param>
        /// <param name="message">Message of the registration</param>
        /// <param name="taskId">Task identifier to add to</param>
        /// <returns>A JsonResult including the inserted work unit</returns>
        public ActionResult Insert(DateTime? date, double hours, string message, int taskId)
        {
            // Prepare the envelope with a faulty state
            var _result = new JsonEnvelope<bool> { Success = false, Data = false, Message = "No insert" };

            string _unique = string.Format("{0}{1}{2}{3}", date, hours, message, taskId);

            if (Session["LastRegistration"] != null && _unique == Session["LastRegistration"].ToString())
            {
                // Dublicate
                _result = new JsonEnvelope<bool>
                {
                    Success = false,
                    Message = string.Empty
                };

                return new JsonResult { Data = _result, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }

            Session["LastRegistration"] = _unique;

            // Construct the work unit object
            var _unit = new WorkUnit();
            _unit.TaskID = taskId;
            _unit.TaskIDSpecified = true;
            _unit.StartDateTime = date.Value;
            _unit.StartDateTimeSpecified = true;
            _unit.GUID = Guid.NewGuid().ToString();
            _unit.EmployeeInitials = SessionHelper.Instance.Initials;
            _unit.Description = message;
            _unit.EndDateTime = date.Value.AddHours(hours);
            _unit.EndDateTimeSpecified = true;
            _unit.Duration = System.Xml.XmlConvert.ToString(TimeSpan.FromHours(hours)); // Do necessary convertion to fit a TimeSpan object

            // Execute the insert request
            var _response = SessionHelper.Instance.ProjectManagementClient.InsertWork(new[] { _unit }, 0, SessionHelper.Instance.ProjectManagementToken);

            // Check if the response was correct
            if (_response.ResponseState == ExecutionStatus.Success)
            {
                // Yes, recreate the envelope
                _result = new JsonEnvelope<bool>
                {
                    Success = true,
                    Message = string.Empty
                };
            }
            else if (_response.ErrorCode == 20003)
            {
                // Token not valid anymore.
                FormsAuthentication.SignOut();
            }
            else
            {
                // No, take the first error message
                _result.Message = _response.Messages.FirstOrDefault().Message;
                _result.Success = false;
            }

            // Return the data as JSON
            return new JsonResult { Data = _result, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
Beispiel #36
0
    /*
     * globaalaas uzvediibas FSM (finite-state-machine)
     * @todo -- stack baased ? ---paartaisiishu, ja atradiishu vismaz 12 iemeslus
     *
     */
    private void thinkAbout()
    {
        Room room = null;

        switch(CurrentState) {
        //---------------------------------------------------------------
        case AgentStates.idling:
            isCraving = -1; //nemeklee nekaadu resursu
            workUnit = null;

            int numResourceShortages = Needs.Shortage.Count(c => c); // ezoteeriskaa veidaa izskaita cik ir TRUE shajaa masiivaa - tik mums ir resursu, kas iet uz galu un jaaiet tos papildinaat
            if(numResourceShortages > 0){ //meklees sev resursus
                CurrentState = AgentStates.choosingResourceDestination;

            } else if(idlingFor > 0){ //pagaidiis bezdarbiibaa

                idlingFor -= Time.deltaTime;
                //bodyAnimator.SetBool("waving", true);

            } else if(workManagerScript.IsThereWorkAvailable()) { //ir kaads darbinsh pieejams
            //    print("ir kaads darbinsh");
                CurrentState = AgentStates.choosingWorkDestination;

            } else { //ja nav jaameklee resursus, tad izveeleesies nejaushu galapunktu un tur pagaidiis
                CurrentState = AgentStates.choosingRandomDestination;
                idlingFor = Random.Range(1, 3);
                //bodyAnimator.SetBool("waving", false);

               // print("STATE:idling + choseRND");
            }
            //print("STATE:idling");
            break;
            //---------------------------------------------------------------
        case AgentStates.choosingRandomDestination:

            room = levelscript.roomWhereIcanDoThis(-1); //dabuus nejaushu telpa

            if(room != null) {
                Vector2 rc = levelscript.randomCubeInThisRoom(room); //randomcube - nejaushss kubiks atrastajaa telpaa
                if(GoThere(rc.x, rc.y) == -1){ // kljuuda - agjents neatrodas uz grida
                    CurrentState = AgentStates.offTheGrid;
                    break;
                }

             //   print("rooom "  + Mathf.RoundToInt(room.transform.position.x) + ", " + Mathf.RoundToInt(room.transform.position.y) + "randCube "  + Mathf.RoundToInt(rc.x) + ", " + Mathf.RoundToInt(rc.y));
              // print("RANDrooom "  + (room.transform.position.x) + ", " + (room.transform.position.y) + "   RANDcube "  + (rc.x) + ", " + (rc.y));

                CurrentState = AgentStates.traveling;
            } else {
                CurrentState = AgentStates.idling; //nav pat 1 nejaushas telpas, nu tad neko - turpina gaidiit
            }

            //print("STATE:choosingRandomDestination");
            break;
            //---------------------------------------------------------------
        case AgentStates.choosingResourceDestination:
            //jaaatrod TUVAAKAA telpa, kas apmierina vajadziibu peec resursa

            for(int need = 0; need < AgentNeeds.numTypes; need++) { //iet cauri visaam agjentvajadziibaam
                if(Needs.Shortage[need]){ //shis resurss truukst, to ir jaaiet mekleet | pirmaas vajadziibas ir svariigaakas (jo taas apskata sekvencionaali, varbuut vajag randomizeet seciibu ikreizi ?)

                    room = levelscript.roomWhereIcanDoThis(need);
                    if(room != null){ //ir atrasta sho vajadziibu apmierinosha telpa
                        isCraving = need; //pieseivos kuru vajadziibu ies apmierinaat - lai zinaatu, ka jaait prom, tikliidz TAA ir apmierinaata
                        break; //neapskata paareejaas vajadziibas
                    }
                }
            }

            if(room != null){  //jaaiet uz atrasto telpu
                Vector2 rc = levelscript.randomCubeInThisRoom(room); //randomcube - nejaushss kubiks atrastajaa telpaa
                if(GoThere(rc.x, rc.y) == -1){ // kljuuda - agjents neatrodas uz grida
                    CurrentState = AgentStates.offTheGrid;
                    break;
                }
                CurrentState = AgentStates.traveling;
               // print("atrada  " + rc.x + ","  + rc.y);
            } else {
                CurrentState = AgentStates.idling; //neko neatrada - jaaiet neko nedariit
              //  print("neatrada");
            }

           // print("STATE:choosingResourceDestination craving=" + isCraving);
            break;
            //---------------------------------------------------------------
        case AgentStates.choosingWorkDestination:
            //print("STATE:choosingWorkDestination ");

            workUnit = null;

            try{
                workUnit = workManagerScript.GetWork(this);
                if(workUnit != null){

                    if(GoThere(workUnit.BestPositionToStandWhileWorking.x, workUnit.BestPositionToStandWhileWorking.y) == -1){ // iet uz noraadiito darbavietu (ja -1 tad Agjents neatrodas uz grida, jaaiet sho glaabt)
                        CurrentState = AgentStates.offTheGrid;
                        break;
                    }

                    CurrentState = AgentStates.traveling;
                    workUnit.ReserveWork(true,this);

                 //   print("ir straadaashana " + workUnit + "  @" + workUnit.parentGameobject.transform + "  bestPOS " + workUnit.BestPositionToStandWhileWorking);

                } else { //nav neviena briiva,pieejama darbinja
                    CurrentState = AgentStates.idling;
                    break;
                }

            } catch(System.Exception e) { // kjer pathfinding iznjeemumu, ka agjents nemaz neatrodas uz grida
                if(e.Message == "not-on-a-grid"){
                    CurrentState = AgentStates.offTheGrid; //agjents ies glaabties
                }

            }

            break;

            //---------------------------------------------------------------
        case AgentStates.traveling:
            // print("STATE:traveling");
            //kad agjents buus nonaacis galaa, tad vinja staavokli nomainiis moveAbout() metodee nevis sheit; nomainiis uz "arriving"

            break;
           //---------------------------------------------------------------
        case AgentStates.offTheGrid:
            //neatrodas uz navgrida, jaaatrod tuvaakais navgridaa esoshais punts un jaaevakueejas taa virzienaa

            if(offTheGridFor > 0){ //pagaidiis kaadu laicinju, lai neceptu procesoru
                offTheGridFor -= Time.deltaTime;
                break;
            }

            if(levelscript.Navgrid.Count > 0){ //ja ir navgridaa punkti, kur mukt
                //print ("provees tikt uz celja");
                Vector2 closestPoint = new Vector2(0,0);
                float closestDistance = -1;
                float x = transform.position.x;
                float y = transform.position.y;

                foreach(KeyValuePair<Vector4, float> p in levelscript.Navgrid) {
                    if(p.Key.y == y){ //meklee tuvaakos punkts tikai shajaa staavaa
                        float d = levelscript.MapDistanceBetweenPoints(p.Key.x,p.Key.y,x,y);//cik taalu shis navgrida punkts no agjenta
                        if(closestDistance == -1 || d < closestDistance){
                            closestPoint = new Vector2(p.Key.x,p.Key.y); //shis ir tuvaakais navgrida punkts
                            closestDistance = d;
                        }
                    }
                }

                if(closestDistance > -1){
                //    print("atradaam kaadu punktu, kur glaabties");
                    destinationNode = closestPoint;
                    actualRoute.Add(closestPoint); //manuaali izveidoju celju (stur tikai 1 punktu - kur skrienu glaabties)
                    CurrentState = AgentStates.traveling; //peec ieshanas automaatiski staavoklis buus IDLING
                    avatarAnimator.SetBool("fast", true); //manuaalie iesaaku animaaciju
                    //print(x + "," + y + " -> " + closestPoint);
                    break;
                } else {
                  //  print("NEatradaam nevienu punktu, kur glaabties");
                    offTheGridFor = 3; //3 sekundes pagaidiis, liidz meegjinaas atkal, varbuut tad buuus kaut kas uzbuuveets
                }

            }
            break;
           //-----------------------------------------------------------------
        case AgentStates.arriving:

            if(workUnit != null){ //te ieradies darba dariishanaas
             //   print("ieradies straaadaaat");
                workingFor = Random.Range(2,5); //dazhas sekundes pastraadaas
                avatarAnimator.SetBool("working", true);
                CurrentState = AgentStates.working;

                break; //break case

            } else if(isCraving >= 0){//sheit ieradies apmierinaat kaadu vajadziibu

                room = levelscript.roomAtThisPosition(transform.position.x,transform.position.y);  //null vai telpa

                if(room == null){ //atnaacis, bet neatrodas telpaa, hmmm
                    CurrentState = AgentStates.idling;
                 //   print("iatnaacis, bet neatrodas telpaa, hmmm");
                } else { //viss kaartiibaa ir telpaa

                    bool roomIsProviding = false;
                    for(int need = 0; need < AgentNeeds.numTypes; need++) { //iet cauri visaam agjentvajadziibaam
                        if(Needs.Shortage[need]){ //shis resurss truukst
                            if(room.AgentNeedsGeneration[need] > 0){ //telpa dod sho resursu
                                roomIsProviding = true;
                                break;
                            }
                        }
                    }

                    if(roomIsProviding){ //telpa deriiga, saakam eest
                      //  print("telpa deriiga, saakam eest");
                        currentRoom = room; //piekesho telpu, kur atnaacis
                        CurrentState = AgentStates.consumingResource;
                    } else { //telpa neko nedod
                        //print("telpa neko nedod");
                        CurrentState = AgentStates.idling;
                    }

                }

            }  else if(isCraving == -1){ //ir bezmeerkjiigi ieradies
                CurrentState = AgentStates.idling;
                break; //break case
            }

            //print("STATE:arriving");
            break;
            //---------------------------------------------------------------
        case AgentStates.consumingResource:
            // currentRoom -- tikai sheit droshi varu lietot sho mainiigo, jo tas ir uzsists ieprieksheejaa kadraa vieniigajaa IFaa, kas ved uz shejieni

            for(int need = 0; need < AgentNeeds.numTypes; need++) { //iet cauri visaam agjentvajadziibaam

                avatarAnimator.SetBool("eating", true); //pagaidaam ir tikai 1 teereeshanas animaacija - eeshana, visus resursus pateeree eedot - arii miedzinju XD

                Needs.Reserve[need] += currentRoom.AgentNeedsGeneration[need] * Time.deltaTime; //eed visus resursus (kas ir 0 vai pozitiivs skaitlis)

                if(Needs.Reserve[need] > Needs.Max[need]){ //neljauj paareesties, ierobesho maximumu
                    Needs.Reserve[need] = Needs.Max[need];
                }

                if(Needs.Reserve[isCraving] == Needs.Max[isCraving]){ // vajadziiba, kuras deelj naaca uz sho telpu, ir apmierinaata
                    CurrentState = AgentStates.idling;
                    avatarAnimator.SetBool("eating", false);
                }

            }

            //print("STATE:consumingResource");
            break;
            //---------------------------------------------------------------
        case AgentStates.working:

            if(!workUnit.IsOn()){ //darbinsh tiek izsleegts
                CurrentState = AgentStates.idling;
                avatarAnimator.SetBool("working", false);
                workUnit.ReserveWork(false); //padara darbinju pieejamu citiem
                break;
            }

            workingFor -= Time.deltaTime;
            workUnit.DoSomeActualMotherFlippingJob();

            if(workingFor < 0){ //buus gana straadaats
                CurrentState = AgentStates.idling;
                avatarAnimator.SetBool("working", false);
                workUnit.ReserveWork(false);//padara darbinju pieejamu citiem
                break;
            }

            //visa magjija un progress notiek workunit skriptaa

            break;

        }
    }