Пример #1
0
        public static List <WorkRecord> GetRecords(string start, string end, string employee)
        {
            var result         = new List <WorkRecord>();
            var start_splitted = start.Split('_');
            var end_splitted   = end.Split('_');
            var filterBuilder  = Builders <BsonDocument> .Filter;
            var filter         = filterBuilder.Gte("date_time", new DateTime(int.Parse(start_splitted[2]), int.Parse(start_splitted[1]), int.Parse(start_splitted[0]), 0, 0, 0)) &
                                 filterBuilder.Lte("date_time", new DateTime(int.Parse(end_splitted[2]), int.Parse(end_splitted[1]), int.Parse(end_splitted[0]), 23, 59, 59));

            if (employee != "_")
            {
                filter = filter & filterBuilder.Eq("employee_id", employee);
            }
            var sortBuilder = Builders <BsonDocument> .Sort;
            var sort        = sortBuilder.Ascending("date_time").Descending("employee_name");

            List <BsonDocument> documents = MongoHelper.GetDatabase().GetCollection <BsonDocument>("work_records").Find(filter).Sort(sort).ToList();

            foreach (var document in documents)
            {
                var record = new WorkRecord();
                record.Id           = document.GetValue("_id", "").ToString();
                record.EmployeeId   = document.GetValue("employee_id", "").ToString();
                record.EmployeeName = document.GetValue("employee_name", "").ToString();
                record.DateTime     = document.GetValue("date_time").ToUniversalTime();
                record.Type         = document.GetValue("type", "").ToString();
                record.Week         = document.GetValue("week", 0).ToInt32();
                record.Synced       = document.GetValue("synced", false).ToBoolean();
                result.Add(record);
            }
            return(result);
        }
        //method - select Work Records
        public List <WorkRecord> SelectAllWorkRecords()
        {
            List <WorkRecord> list = new List <WorkRecord>();

            //#1 - create connection
            SqlConnection conn = new SqlConnection();

            conn.ConnectionString = "Data Source=.;Initial Catalog=Yi_PD2_ETSDatabase;Integrated Security=True";
            conn.Open();
            using (conn)
            {
                //#2 - create command
                SqlCommand command = new SqlCommand("sp_EmployeesAndEmpHours_SelectAll", conn);
                command.CommandType = System.Data.CommandType.StoredProcedure;

                //#3 - run command
                SqlDataReader reader = command.ExecuteReader();

                //#4 - handle results
                while (reader.Read())
                {
                    //map record to object
                    WorkRecord record = new WorkRecord();
                    record.EmpID      = Convert.ToInt32(reader["EmpID"]);
                    record.EmpHoursID = Convert.ToInt32(reader["EmpHoursID"]);
                    record.FirstName  = Convert.ToString(reader["FirstName"]);
                    record.LastName   = Convert.ToString(reader["LastName"]);
                    record.WorkDate   = Convert.ToDateTime(reader["WorkDate"]);
                    record.Hours      = Convert.ToDouble(reader["Hours"]);
                    //add to list
                    list.Add(record);
                }
                return(list);
            }
        }
Пример #3
0
        public async Task <IActionResult> Edit(string id, [Bind("WorkRid,Promo,NumOfComp,YearsAtCurrComp,YearsRole,TotalWorkingYears")] WorkRecord workRecord)
        {
            if (id != workRecord.WorkRid)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(workRecord);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!WorkRecordExists(workRecord.WorkRid))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(workRecord));
        }
Пример #4
0
        public IActionResult Put(int id, WorkRecord workRecord)
        {
            if (id != workRecord.Id)
            {
                return(BadRequest());
            }

            _workRecordRepository.Update(workRecord);
            return(NoContent());
        }
Пример #5
0
        public IActionResult Post(WorkRecord workRecord)
        {
            var currentUserProfile = GetCurrentUserProfile();

            workRecord.UserProfileId = currentUserProfile.Id;
            workRecord.CreateDate    = DateTime.Now;

            _workRecordRepository.Add(workRecord);
            return(CreatedAtAction(nameof(Get), new { id = workRecord.Id }, workRecord));
        }
Пример #6
0
        public async Task <IActionResult> Create([Bind("WorkRid,Promo,NumOfComp,YearsAtCurrComp,YearsRole,TotalWorkingYears")] WorkRecord workRecord)
        {
            if (ModelState.IsValid)
            {
                _context.Add(workRecord);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(workRecord));
        }
Пример #7
0
        public AddWorkRecordCommand(Guid projectID, Guid taskID, WorkRecord record)
        {
            if (null == record)
            {
                throw new ArgumentNullException("record");
            }

            _projectID = projectID;
            _taskID    = taskID;
            _record    = record;
        }
    public void AddWorkRecord(WorkRecord record)
    {
        // Note: this method doesn't handle case when EndTime is next day
        var      date = record.StarTime.Date;
        DayStats dayStats;

        if (!_days.TryGetValue(date, out dayStats))
        {
            dayStats = new DayStats();
            _days.Add(date, dayStats);
        }
        dayStats.AddWorkRecord(record);
    }
Пример #9
0
        public static WorkRecord InsertRecord(WorkRecord record)
        {
            BsonDocument newRecord = new BsonDocument();

            newRecord.Add("employee_id", record.EmployeeId);
            newRecord.Add("employee_name", record.EmployeeName);
            newRecord.Add("date_time", record.DateTime);
            newRecord.Add("type", record.Type);
            newRecord.Add("week", record.Week);
            newRecord.Add("Synced", record.Synced);
            MongoHelper.GetDatabase().GetCollection <BsonDocument>("work_records").InsertOne(newRecord);
            record.Id = newRecord.GetValue("_id").ToString();
            return(record);
        }
        public JsonResult GetRecords()
        {
            int      start        = int.Parse(HttpContext.Request["start"]);
            int      limit        = int.Parse(HttpContext.Request["limit"]);
            string   employeeCode = HttpContext.Request["Employee"];
            DateTime fromDate     = DateTime.Parse(HttpContext.Request["FromDate"]);
            DateTime toDate       = DateTime.Parse(HttpContext.Request["ToDate"]);

            int workRecordCount = WorkRecord.GetAllCount(employeeCode, fromDate, toDate);
            List <WorkRecord.DTO> workRecordSome = WorkRecord.GetSome(employeeCode, fromDate, toDate, start, limit);

            var result = new { totalProperty = workRecordCount, root = workRecordSome };

            return(Json(result));
        }
        public JsonResult DoMake()
        {
            string EmployeeCode     = HttpContext.Request["EmployeeCode"];
            string WorkCalendarCode = HttpContext.Request["WorkCalendarCode"];
            string FromDateStr      = HttpContext.Request["FromDate"];
            string ToDateStr        = HttpContext.Request["ToDate"];

            DateTime FromDate = DateTime.Parse(FromDateStr);
            DateTime ToDate   = DateTime.Parse(ToDateStr);

            WorkRecord.Make(EmployeeCode, WorkCalendarCode, FromDate, ToDate);

            var resultSuccess = new { success = true, msg = "Make records success!" };

            return(Json(resultSuccess));
        }
        public ActionResult Test(string EmployeeCode, string FromDate, string ToDate)
        {
            ViewData["Title"] = "Report2";

            ViewData["EmployeeCode"] = EmployeeCode;
            ViewData["FromDate"]     = FromDate;
            ViewData["ToDate"]       = ToDate;

            DateTime RealFromDate = DateTime.Parse(FromDate);
            DateTime RealToDate   = DateTime.Parse(ToDate);

            List <WorkRecord.DTO> workRecordSome = WorkRecord.GetSome(EmployeeCode, RealFromDate, RealToDate);

            ViewData["Records"] = workRecordSome;

            return(View());
        }
Пример #13
0
        private static void WorkTableUpdate(WorkRecord workRecord)
        {
            //string sql = @"MERGE Work AS target USING (SELECT @SerialNO as SerialNO, @MachineId as MachineId, @Layer as Layer, @HoleCount as HoleCount,
            //            @LastTime as LastTime)  AS source ON (target.SerialNO = source.SerialNO) WHEN MATCHED THEN UPDATE SET
            //            HoleCount = source.HoleCount  WHEN NOT MATCHED THEN INSERT (SerialNO, MachineId, Layer, HoleCount, LastTime)
            //            VALUES (source.SerialNO, source.MachineId, source.Layer, source.HoleCount, source.LastTime);";
            //SqlParameter[] param = { new SqlParameter("@SerialNO",workRecord.Id), new SqlParameter("@MachineId", workRecord.MachineId ), new SqlParameter("@Layer", workRecord.Layer ),
            //            new SqlParameter("@HoleCount",workRecord.HoleCount ), new SqlParameter( "@LastTime",workRecord.LastTime ) };
            string sql = @"MERGE Work AS target USING (SELECT @SerialNO as SerialNO, @Layer as Layer, @HoleCount as HoleCount, 
                        @LastTime as LastTime)  AS source ON (target.SerialNO = source.SerialNO) WHEN MATCHED THEN UPDATE SET 
                        HoleCount = source.HoleCount  WHEN NOT MATCHED THEN INSERT (SerialNO, Layer, HoleCount, LastTime) 
                        VALUES (source.SerialNO,  source.Layer, source.HoleCount, source.LastTime);";

            SqlParameter[] param = { new SqlParameter("@SerialNO",  workRecord.Id),        new SqlParameter("@Layer",    workRecord.Layer),
                                     new SqlParameter("@HoleCount", workRecord.HoleCount), new SqlParameter("@LastTime", workRecord.LastTime) };
            SQLHelper.Update(sql, param);
        }
        public void TestAddWorkRecord()
        {
            Project project = new Project("Artigos");

            ExecuteCommand(new AddProjectCommand(project));

            Task task = new Task("Preval�ncia de Objetos");

            ExecuteCommand(new AddTaskCommand(project.ID, task));

            DateTime   startTime = new DateTime(2003, 6, 29, 13, 26, 0);
            DateTime   endTime   = startTime.AddHours(5);
            WorkRecord record    = new WorkRecord(startTime, endTime);

            ExecuteCommand(new AddWorkRecordCommand(project.ID, task.ID, record));
            AssertEquals(1, task.WorkRecords.Count);
            AssertSame(record, task.WorkRecords[0]);
        }
 public void AddWorkRecord(WorkRecord record)
 {
     // Note: this method doesn't handle case when EndTime is next day
     // handle "middle" hours, they are all full
     for (int hour = record.StarTime.Hour + 1; hour < record.EndTime.Hour; hour++)
     {
         TotalMinutes[hour] += 60;
     }
     // handle first and last hours that might be not full
     if (record.StarTime.Hour == record.EndTime.Hour)
     {
         TotalMinutes[record.StarTime.Hour] += record.EndTime.Minute - record.StarTime.Minute;
     }
     else
     {
         TotalMinutes[record.StarTime.Hour] += 60 - record.StarTime.Minute;
         TotalMinutes[record.EndTime.Hour]  += record.EndTime.Minute;
     }
 }
Пример #16
0
        private void InitButtons()
        {
            List <WorkRecord.DTO> dtos = WorkRecord.GetFive(EmployeeCode, DateTime.Now);

            buttons.Add(button0);
            buttons.Add(button1);
            buttons.Add(button2);
            buttons.Add(button3);
            buttons.Add(button4);

            int i = 0;

            foreach (WorkRecord.DTO dto in dtos)
            {
                buttons[i].Content  = dto.WorkPoint;
                buttons[i].Content += "(" + dto.Status + ")";
                buttons[i].Tag      = dto.ID;
                i++;
            }
        }
Пример #17
0
        public void Add(WorkRecord workRecord)
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"INSERT INTO WorkRecord (UserProfileId, JobId, CreateDate, NoteText, TimeOnJob)
                                        OUTPUT INSERTED.ID
                                        VALUES (@UserProfileId, @JobId, @CreateDate, @NoteText, @TimeOnJob)";
                    DbUtils.AddParameter(cmd, "@UserProfileId", workRecord.UserProfileId);
                    DbUtils.AddParameter(cmd, "@JobId", workRecord.JobId);
                    DbUtils.AddParameter(cmd, "@CreateDate", workRecord.CreateDate);
                    DbUtils.AddParameter(cmd, "@NoteText", workRecord.NoteText);
                    DbUtils.AddParameter(cmd, "@TimeOnJob", workRecord.TimeOnJob);


                    workRecord.Id = (int)cmd.ExecuteScalar();
                }
            }
        }
Пример #18
0
        public void Update(WorkRecord workRecord)
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                        UPDATE WorkRecord
                           SET NoteText = @NoteText,
                                TimeOnJob = @TimeOnJob
                         WHERE Id = @Id";



                    DbUtils.AddParameter(cmd, "@NoteText", workRecord.NoteText);
                    DbUtils.AddParameter(cmd, "@TimeOnJob", workRecord.TimeOnJob);
                    DbUtils.AddParameter(cmd, "@Id", workRecord.Id);
                    cmd.ExecuteNonQuery();
                }
            }
        }
Пример #19
0
        public WorkRecord GetById(int id)
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                          SELECT  UserProfileId, JobId, CreateDate, NoteText, TimeOnJob
                            FROM WorkRecord 
                           WHERE Id = @Id";

                    DbUtils.AddParameter(cmd, "@Id", id);

                    var reader = cmd.ExecuteReader();

                    WorkRecord workRecord = null;
                    if (reader.Read())
                    {
                        workRecord = new WorkRecord()
                        {
                            Id            = id,
                            UserProfileId = DbUtils.GetInt(reader, "UserProfileId"),
                            JobId         = DbUtils.GetInt(reader, "JobId"),
                            CreateDate    = DbUtils.GetDateTime(reader, "CreateDate"),
                            NoteText      = DbUtils.GetString(reader, "NoteText"),
                            TimeOnJob     = DbUtils.GetDecimal(reader, "TimeOnJob"),
                        };
                    }

                    reader.Close();

                    return(workRecord);
                }
            }
        }
        public void SetRecord(WorkRecord record)
        {
            // TO ASK: shall we set a field of the record?
            // We need sucha method:
//>>>>>>>>>>// User UserOfWorkRecord(WorkRecord record)
            EnsureEmployeeWithSpecifiedLogin(record.EmployeeDescription.Employee.Login);
            _db.SetRecord(record);
        }
Пример #21
0
        public ApplicationDataModel.ADM.ApplicationDataModel Import(ISO11783_TaskData taskData)
        {
            ISOTaskData    = taskData;
            UniqueIDMapper = new UniqueIdMapper(ISOTaskData.LinkList);

            AdaptDataModel         = new ApplicationDataModel.ADM.ApplicationDataModel();
            AdaptDataModel.Catalog = new Catalog()
            {
                Description = taskData.FilePath
            };
            AdaptDataModel.Documents = new Documents();

            //Comments
            CodedCommentListMapper commentListMapper = new CodedCommentListMapper(this);
            CodedCommentMapper     commentMapper     = new CodedCommentMapper(this, commentListMapper);

            //Crops - several dependencies require import prior to Products
            IEnumerable <ISOCropType> crops = taskData.ChildElements.OfType <ISOCropType>();

            if (crops.Any())
            {
                CropTypeMapper cropMapper = new CropTypeMapper(this, ProductGroupMapper);
                AdaptDataModel.Catalog.Crops.AddRange(cropMapper.ImportCropTypes(crops));
            }

            //Products
            IEnumerable <ISOProduct> products = taskData.ChildElements.OfType <ISOProduct>();

            if (products.Any())
            {
                ProductMapper         productMapper = new ProductMapper(this, ProductGroupMapper);
                IEnumerable <Product> adaptProducts = productMapper.ImportProducts(products);
                AdaptDataModel.Catalog.Products.AddRange(adaptProducts.Where(p => !AdaptDataModel.Catalog.Products.Contains(p)));
            }

            //Growers
            IEnumerable <ISOCustomer> customers = taskData.ChildElements.OfType <ISOCustomer>();

            if (customers.Any())
            {
                CustomerMapper customerMapper = new CustomerMapper(this);
                AdaptDataModel.Catalog.Growers.AddRange(customerMapper.Import(customers));
            }

            //Farms
            IEnumerable <ISOFarm> farms = taskData.ChildElements.OfType <ISOFarm>();

            if (farms.Any())
            {
                FarmMapper farmMapper = new FarmMapper(this);
                AdaptDataModel.Catalog.Farms.AddRange(farmMapper.Import(farms));
            }

            //Fields & Cropzones
            IEnumerable <ISOPartfield> partFields = taskData.ChildElements.OfType <ISOPartfield>();

            if (partFields.Any())
            {
                PartfieldMapper partFieldMapper = new PartfieldMapper(this);
                AdaptDataModel.Catalog.Fields.AddRange(partFieldMapper.ImportFields(partFields));
                AdaptDataModel.Catalog.CropZones.AddRange(partFieldMapper.ImportCropZones(partFields));
            }

            //Devices
            IEnumerable <ISODevice> devices = taskData.ChildElements.OfType <ISODevice>();

            if (devices.Any())
            {
                DeviceElementHierarchies = new DeviceElementHierarchies(devices, RepresentationMapper);

                DeviceMapper deviceMapper = new DeviceMapper(this);
                AdaptDataModel.Catalog.DeviceModels.AddRange(deviceMapper.ImportDevices(devices));
            }

            //Workers
            IEnumerable <ISOWorker> workers = taskData.ChildElements.OfType <ISOWorker>();

            if (workers.Any())
            {
                WorkerMapper workerMapper = new WorkerMapper(this);
                AdaptDataModel.Catalog.Persons.AddRange(workerMapper.Import(workers));
            }


            //Cultural Practices
            IEnumerable <ISOCulturalPractice> practices = taskData.ChildElements.OfType <ISOCulturalPractice>();

            if (practices.Any())
            {
                foreach (ISOCulturalPractice cpc in practices)
                {
                    (AdaptDataModel.Documents.WorkOrders as List <WorkOrder>).Add(new WorkOrder()
                    {
                        Description = cpc.CulturalPracticeDesignator
                    });
                }
            }

            //OperationTechniques
            IEnumerable <ISOOperationTechnique> techniques = taskData.ChildElements.OfType <ISOOperationTechnique>();

            if (techniques.Any())
            {
                foreach (ISOOperationTechnique otq in techniques)
                {
                    (AdaptDataModel.Documents.WorkOrders as List <WorkOrder>).Add(new WorkOrder()
                    {
                        Description = otq.OperationTechniqueDesignator
                    });
                }
            }

            IEnumerable <ISOTask> prescribedTasks = taskData.ChildElements.OfType <ISOTask>().Where(t => t.IsWorkItemTask);
            IEnumerable <ISOTask> loggedTasks     = taskData.ChildElements.OfType <ISOTask>().Where(t => t.IsLoggedDataTask || t.TimeLogs.Any());

            if (prescribedTasks.Any() || loggedTasks.Any())
            {
                TaskMapper taskMapper = new TaskMapper(this);
                if (prescribedTasks.Any())
                {
                    //Prescribed Tasks
                    IEnumerable <WorkItem> workItems = taskMapper.ImportWorkItems(prescribedTasks);
                    AdaptDataModel.Documents.WorkItems = workItems;
                }

                if (loggedTasks.Any())
                {
                    //Logged Tasks
                    IEnumerable <LoggedData> loggedDatas = taskMapper.ImportLoggedDatas(loggedTasks);
                    AdaptDataModel.Documents.LoggedData = loggedDatas;

                    //Create Work Records for Logged Tasks
                    List <WorkRecord> workRecords = new List <WorkRecord>();
                    foreach (LoggedData data in loggedDatas)
                    {
                        WorkRecord record = new WorkRecord();
                        record.LoggedDataIds.Add(data.Id.ReferenceId);
                        if (data.SummaryId.HasValue)
                        {
                            record.SummariesIds.Add(data.SummaryId.Value);
                            Summary summary = AdaptDataModel.Documents.Summaries.FirstOrDefault(s => s.Id.ReferenceId == data.SummaryId);
                            if (summary != null)
                            {
                                summary.WorkRecordId = record.Id.ReferenceId;
                            }
                        }
                        workRecords.Add(record);
                    }
                    AdaptDataModel.Documents.WorkRecords = workRecords;
                }
            }

            return(AdaptDataModel);
        }
Пример #22
0
        public JsonResult Post([FromBody] WorkRecord record)
        {
            var result = RecordManager.InsertRecord(record);

            return(new JsonResult(result));
        }
Пример #23
0
        public ApplicationDataModel.ADM.ApplicationDataModel Import(ISO11783_TaskData taskData)
        {
            if (Properties == null)
            {
                Properties = new Properties();
            }

            ISOTaskData    = taskData;
            UniqueIDMapper = new UniqueIdMapper(ISOTaskData.LinkList);

            AdaptDataModel         = new ApplicationDataModel.ADM.ApplicationDataModel();
            AdaptDataModel.Catalog = new Catalog()
            {
                Description = taskData.FilePath
            };
            AdaptDataModel.Documents = new Documents();

            //Comments
            CodedCommentListMapper commentListMapper = new CodedCommentListMapper(this);
            CodedCommentMapper     commentMapper     = new CodedCommentMapper(this, commentListMapper);

            //Crops - several dependencies require import prior to Products
            IEnumerable <ISOCropType> crops = taskData.ChildElements.OfType <ISOCropType>();

            if (crops.Any())
            {
                CropTypeMapper cropMapper = new CropTypeMapper(this, ProductGroupMapper);
                AdaptDataModel.Catalog.Crops.AddRange(cropMapper.ImportCropTypes(crops));
            }

            //Products
            IEnumerable <ISOProduct> products = taskData.ChildElements.OfType <ISOProduct>();

            if (products.Any())
            {
                ProductMapper         productMapper = new ProductMapper(this, ProductGroupMapper);
                IEnumerable <Product> adaptProducts = productMapper.ImportProducts(products);
                AdaptDataModel.Catalog.Products.AddRange(adaptProducts.Where(p => !AdaptDataModel.Catalog.Products.Contains(p)));
            }

            //Growers
            IEnumerable <ISOCustomer> customers = taskData.ChildElements.OfType <ISOCustomer>();

            if (customers.Any())
            {
                CustomerMapper customerMapper = new CustomerMapper(this);
                AdaptDataModel.Catalog.Growers.AddRange(customerMapper.Import(customers));
            }

            //Farms
            IEnumerable <ISOFarm> farms = taskData.ChildElements.OfType <ISOFarm>();

            if (farms.Any())
            {
                FarmMapper farmMapper = new FarmMapper(this);
                AdaptDataModel.Catalog.Farms.AddRange(farmMapper.Import(farms));
            }

            //Fields & Cropzones
            IEnumerable <ISOPartfield> partFields = taskData.ChildElements.OfType <ISOPartfield>();

            if (partFields.Any())
            {
                PartfieldMapper partFieldMapper = new PartfieldMapper(this);
                AdaptDataModel.Catalog.Fields.AddRange(partFieldMapper.ImportFields(partFields));
                AdaptDataModel.Catalog.CropZones.AddRange(partFieldMapper.ImportCropZones(partFields, crops));
            }

            //Devices

            IEnumerable <ISODevice> devices = taskData.ChildElements.OfType <ISODevice>();

            if (devices.Any())
            {
                //See explanation of MergeSingleBinsIntoBoom in DeviceElementHierarchy
                bool mergeBins;
                if (Properties == null || !bool.TryParse(Properties.GetProperty(MergeSingleBinsIntoBoom), out mergeBins))
                {
                    mergeBins = true;
                }

                //Load the internal objects modeling hierarchies of DETs per DVC
                DeviceElementHierarchies = new DeviceElementHierarchies(devices,
                                                                        RepresentationMapper,
                                                                        mergeBins,
                                                                        taskData.ChildElements.OfType <ISOTask>().SelectMany(t => t.TimeLogs),
                                                                        BaseFolder);

                //Import the ISO DVC & DET data into the actual ADAPT models.
                //During DET import, we use the DeviceElementHierarchies from above to map the actual hierarchies and fill in details.
                DeviceMapper deviceMapper = new DeviceMapper(this);
                AdaptDataModel.Catalog.DeviceModels.AddRange(deviceMapper.ImportDevices(devices));
            }

            //Workers
            IEnumerable <ISOWorker> workers = taskData.ChildElements.OfType <ISOWorker>();

            if (workers.Any())
            {
                WorkerMapper workerMapper = new WorkerMapper(this);
                AdaptDataModel.Catalog.Persons.AddRange(workerMapper.Import(workers));
            }


            //Cultural Practices
            IEnumerable <ISOCulturalPractice> practices = taskData.ChildElements.OfType <ISOCulturalPractice>();

            if (practices.Any())
            {
                foreach (ISOCulturalPractice cpc in practices)
                {
                    (AdaptDataModel.Documents.WorkOrders as List <WorkOrder>).Add(new WorkOrder()
                    {
                        Description = cpc.CulturalPracticeDesignator
                    });
                }
            }

            //OperationTechniques
            IEnumerable <ISOOperationTechnique> techniques = taskData.ChildElements.OfType <ISOOperationTechnique>();

            if (techniques.Any())
            {
                foreach (ISOOperationTechnique otq in techniques)
                {
                    (AdaptDataModel.Documents.WorkOrders as List <WorkOrder>).Add(new WorkOrder()
                    {
                        Description = otq.OperationTechniqueDesignator
                    });
                }
            }

            IEnumerable <ISOTask> prescribedTasks = taskData.ChildElements.OfType <ISOTask>().Where(t => t.IsWorkItemTask);
            IEnumerable <ISOTask> loggedTasks     = taskData.ChildElements.OfType <ISOTask>().Where(t => t.IsLoggedDataTask || t.TimeLogs.Any());

            if (prescribedTasks.Any() || loggedTasks.Any())
            {
                TaskMapper taskMapper = new TaskMapper(this);
                if (prescribedTasks.Any())
                {
                    //Prescribed Tasks
                    IEnumerable <WorkItem> workItems = taskMapper.ImportWorkItems(prescribedTasks);
                    AdaptDataModel.Documents.WorkItems = workItems;
                }

                if (loggedTasks.Any())
                {
                    //Logged Tasks
                    IEnumerable <LoggedData> loggedDatas = taskMapper.ImportLoggedDatas(loggedTasks);
                    AdaptDataModel.Documents.LoggedData = loggedDatas;

                    //Create Work Records for Logged Tasks
                    List <WorkRecord> workRecords = new List <WorkRecord>();
                    foreach (LoggedData data in loggedDatas)
                    {
                        WorkRecord record = new WorkRecord();
                        record.LoggedDataIds.Add(data.Id.ReferenceId);
                        if (data.SummaryId.HasValue)
                        {
                            record.SummariesIds.Add(data.SummaryId.Value);
                            Summary summary = AdaptDataModel.Documents.Summaries.FirstOrDefault(s => s.Id.ReferenceId == data.SummaryId);
                            if (summary != null)
                            {
                                summary.WorkRecordId = record.Id.ReferenceId;
                            }
                        }

                        //Export Derived UTC Delta as a ContextItem
                        //The value will be as accurate as the clock settings and thus terming "Delta" vs "Offset" to underscore this is not an accurate UTC offset for the local timezone
                        //Not rounding value so that relatively accurate GPS UTC values can be reverse calculated from this value.
                        string      offset      = GPSToLocalDelta.HasValue ? GPSToLocalDelta.Value.ToString(CultureInfo.InvariantCulture) : "no data";
                        ContextItem contextItem = new ContextItem()
                        {
                            Code = "GPSUTC_Local_Delta", Value = offset, ValueUOM = "hr"
                        };
                        record.ContextItems.Add(contextItem);

                        workRecords.Add(record);
                    }
                    AdaptDataModel.Documents.WorkRecords = workRecords;
                }
            }

            return(AdaptDataModel);
        }
Пример #24
0
    public List<WorkRecord> SearchStaffWorkRecord(string StaffID,string ThisDate)
    {
        List<WorkRecord> returnValue = new List<WorkRecord>();
        DataBase Base = new DataBase();
        using (SqlConnection Sqlconn = new SqlConnection(Base.GetConnString()))
        {
            try
            {
                Sqlconn.Open();
                string sql = "select  CAST(CreateFileDate AS smalldatetime ) as CreateFileDate  FROM WorkRecord where staffid = @StaffID and  CAST(CreateFileDate AS date ) = @ThisDate order by CreateFileDate ";
                SqlCommand cmd = new SqlCommand(sql, Sqlconn);
                cmd.Parameters.Add("@StaffID", SqlDbType.Int).Value = Chk.CheckStringtoIntFunction(StaffID);
                cmd.Parameters.Add("@ThisDate", SqlDbType.Date).Value = Chk.CheckStringtoDateFunction(ThisDate);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    WorkRecord addValue = new WorkRecord();
                    addValue.CreateFileDate = DateTime.Parse(dr["CreateFileDate"].ToString()).ToString("HH:mm");

                    //addValue.sUnit = dr["Unit"].ToString();
                    //addValue.sJob = dr["WorkItem"].ToString();
                    //addValue.FileDate = DateTime.Parse(dr["FileDate"].ToString()).ToString("yyyy-MM-dd");
                    //addValue.Phone = dr["Phone"].ToString();
                    //addValue.officeDate = DateTime.Parse(dr["AppointmentDate"].ToString()).ToString("yyyy-MM-dd");
                    //addValue.resignDate = DateTime.Parse(dr["ResignationDate"].ToString()).ToString("yyyy-MM-dd");
                    returnValue.Add(addValue);
                }
                dr.Close();
                Sqlconn.Close();
            }
            catch (Exception e)
            {
                string Ex = e.Message.ToString();
                //StaffDataList addValue = new StaffDataList();
                //addValue.checkNo = "-1";
                //addValue.errorMsg = e.Message.ToString();
                //returnValue.Add(addValue);
            }

        }

        return returnValue;
    }
 public void SetRecordDontAllowToAddNewEmployeeDescription()
 {
     WorkRecord record = new WorkRecord();
     record.EmployeeDescription = new EmployeeDescription();
     Dao.SetRecord(record);
 }
Пример #26
0
 public void SetUp()
 {
     _record = new WorkRecord(_startTime, _endTime);
 }
 private void PrepareForRemoving(String Login)
 {
     PublicUserInfo userInfo = new PublicUserInfo() { Login = "******" };
     User user = new User() { PublicUserInfo = userInfo };
     Project project = new Project() { Manager = userInfo };
     EmployeeDescription employeeDescription = new EmployeeDescription() { Employee = userInfo, Project = project };
     Contract contract = new Contract() { Creator = userInfo, Employee = userInfo, Project = project };
     WorkRecord record = new WorkRecord { EmployeeDescription = employeeDescription, MinutesWorked = 12 };
     Summary summary = new Summary { EmployeeDescription = employeeDescription };
     Dao.SetUser(user);
     Assert.IsFalse(Dao.GetEmployeeDescriptions(user).Count > 0);
     Assert.IsFalse(Dao.GetRecords(user).Count > 0);
     Assert.IsFalse(Dao.GetSummaries(user).Count > 0);
     Assert.IsFalse(Dao.GetContracts(user).Count > 0);
     Dao.SetProject(project);
     Dao.SetEmployeeDescription(employeeDescription);
     Dao.SetRecord(record);
     Dao.SetSummary(summary);
     Dao.SetContract(contract);
     Assert.IsTrue(Dao.GetEmployeeDescriptions(user).Count > 0);
     Assert.IsTrue(Dao.GetRecords(user).Count > 0);
     Assert.IsTrue(Dao.GetContracts(user).Count > 0);
     Assert.IsTrue(Dao.GetSummaries(user).Count > 0);
 }
 public void RelationsFromWorkRecordMustExist()
 {
     WorkRecord record = new WorkRecord();
     Dao.SetRecord(record);
 }
Пример #29
0
        static void Main(string[] args)
        {
            var testData = JArray.Parse(File.ReadAllText("data.json"));

            string applicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
            var    pluginFactory   = new PluginFactory(applicationPath);

            var admPlugin = pluginFactory.GetPlugin("ADMPlugin");

            admPlugin.Initialize();

            ApplicationDataModel export = new ApplicationDataModel();

            export.Catalog   = new Catalog();
            export.Documents = new Documents();
            List <WorkRecord> workRecords = new List <WorkRecord>();
            List <Summary>    summaries   = new List <Summary>();

            // All of these records are for the same Grower/Farm/Field/CropZone/CropYear so I'm just
            // pulling the common info from the first record.

            #region Create a "crop year" TimeScope to tag each of the WorkRecords with.
            TimeScope cropYear = new TimeScope();
            UniqueId  ourId    = new UniqueId();
            ourId.Id         = testData[0]["CropYear"].ToString();
            ourId.IdType     = IdTypeEnum.String;
            ourId.Source     = "www.somecompany.com";
            ourId.SourceType = IdSourceTypeEnum.URI;
            cropYear.Id.UniqueIds.Add(ourId);
            cropYear.Description = testData[0]["CropYear"].ToString();
            cropYear.DateContext = DateContextEnum.CropSeason;
            export.Catalog.TimeScopes.Add(cropYear);
            #endregion

            #region Create the Grower/Farm/Field/CropZone objects for this group of applications
            Grower grower = new Grower();
            ourId            = new UniqueId();
            ourId.Id         = testData[0]["ApplicationId"]["DataSourceId"].ToString();
            ourId.IdType     = IdTypeEnum.UUID;
            ourId.Source     = "www.somecompany.com";
            ourId.SourceType = IdSourceTypeEnum.URI;
            grower.Id.UniqueIds.Add(ourId);
            grower.Name = testData[0]["GrowerName"].ToString();
            export.Catalog.Growers.Add(grower);

            Farm farm = new Farm();
            ourId            = new UniqueId();
            ourId.Id         = testData[0]["FarmId"]["Id"].ToString();
            ourId.IdType     = IdTypeEnum.UUID;
            ourId.Source     = "www.somecompany.com";
            ourId.SourceType = IdSourceTypeEnum.URI;
            farm.Id.UniqueIds.Add(ourId);
            farm.Description = testData[0]["FarmName"].ToString();
            farm.GrowerId    = grower.Id.ReferenceId;
            export.Catalog.Farms.Add(farm);

            Field field = new Field();
            ourId            = new UniqueId();
            ourId.Id         = testData[0]["FieldId"].ToString();
            ourId.IdType     = IdTypeEnum.UUID;
            ourId.Source     = "www.somecompany.com";
            ourId.SourceType = IdSourceTypeEnum.URI;
            field.Id.UniqueIds.Add(ourId);
            field.Description = testData[0]["FieldName"].ToString();
            field.FarmId      = farm.Id.ReferenceId;
            export.Catalog.Fields.Add(field);

            Crop crop = new Crop();
            ourId            = new UniqueId();
            ourId.Id         = testData[0]["CropId"]["Id"].ToString();
            ourId.IdType     = IdTypeEnum.UUID;
            ourId.Source     = "www.somecompany.com";
            ourId.SourceType = IdSourceTypeEnum.URI;
            crop.Id.UniqueIds.Add(ourId);
            crop.Name = testData[0]["Crop"].ToString();
            // Add EPPO code as ContextItem at some point in the future
            export.Catalog.Crops.Add(crop);

            CropZone cropZone = new CropZone();
            ourId            = new UniqueId();
            ourId.Id         = testData[0]["CropZoneId"].ToString();
            ourId.IdType     = IdTypeEnum.UUID;
            ourId.Source     = "www.somecompany.com";
            ourId.SourceType = IdSourceTypeEnum.URI;
            cropZone.Id.UniqueIds.Add(ourId);
            cropZone.Description = testData[0]["CropZoneName"].ToString();
            cropZone.FieldId     = field.Id.ReferenceId;
            cropZone.CropId      = crop.Id.ReferenceId;
            cropZone.TimeScopes.Add(cropYear);
            string areaString = testData[0]["AreaApplied"].ToString();
            double area       = Convert.ToDouble(areaString);
            cropZone.Area = new NumericRepresentationValue(RepresentationInstanceList.vrReportedFieldArea.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ac1"), area));
            export.Catalog.CropZones.Add(cropZone);
            #endregion

            // Foreach Application
            var applicationIds = ((from c in testData select c["ApplicationId"]["Id"]).Distinct()).ToList();
            foreach (var applicationId in applicationIds)
            {
                var appliedProducts = (from c in testData where (string)c["ApplicationId"]["Id"] == applicationId.ToString() select c).ToList();

                // Create a WorkRecord and Summary (ADAPT's version of an Application)
                WorkRecord workRecord = new WorkRecord();
                ourId            = new UniqueId();
                ourId.Id         = appliedProducts[0]["ApplicationId"]["Id"].ToString();
                ourId.IdType     = IdTypeEnum.UUID;
                ourId.Source     = "www.somecompany.com";
                ourId.SourceType = IdSourceTypeEnum.URI;
                workRecord.Id.UniqueIds.Add(ourId);
                workRecord.Description = appliedProducts[0]["ApplicationName"].ToString();
                workRecord.TimeScopes.Add(cropYear);

                TimeScope timingEvent = new TimeScope();
                timingEvent.DateContext = DateContextEnum.TimingEvent;
                timingEvent.Description = appliedProducts[0]["TimingEvent"].ToString();
                workRecord.TimeScopes.Add(timingEvent);

                TimeScope startDate = new TimeScope();
                startDate.DateContext = DateContextEnum.ActualStart;
                startDate.TimeStamp1  = DateTime.Parse(appliedProducts[0]["StartDate"].ToString());
                workRecord.TimeScopes.Add(startDate);

                TimeScope endDate = new TimeScope();
                endDate.DateContext = DateContextEnum.ActualEnd;
                endDate.TimeStamp1  = DateTime.Parse(appliedProducts[0]["EndDate"].ToString());
                workRecord.TimeScopes.Add(endDate);

                Summary summary = new Summary();
                // This property linking the Summary to its parent WorkRecord doesn't exist in ADAPT 1.1.0.8.
                // Slated to be added in next release.
                // summary.WorkRecordId = workRecord.Id.ReferenceId;

                // This property linking the Summary to its Grower doesn't exist in ADAPT 1.1.0.8.
                // Slated to be added in next release.
                // summary.GrowerId = grower.Id.ReferenceId;

                summary.FarmId     = farm.Id.ReferenceId;
                summary.FieldId    = field.Id.ReferenceId;
                summary.CropZoneId = cropZone.Id.ReferenceId;



                // Foreach Product
                foreach (var appliedProduct in appliedProducts)
                {
                    //Note that Manufacturer is not a required property for a given product.
                    Manufacturer manufacturer  = null;
                    var          manufacturers = export.Catalog.Manufacturers.Where(x => (x.Description == appliedProduct["Manufacturer"].ToString())).ToList();
                    if (manufacturers.Count > 0)
                    {
                        manufacturer = manufacturers[0];
                    }
                    else
                    {
                        manufacturer = new Manufacturer();
                        ourId        = new UniqueId();
                        // Couldn't find Manufacturer id in your data
                        ourId.Id         = "00000000-0000-0000-0000-000000000000";
                        ourId.IdType     = IdTypeEnum.UUID;
                        ourId.Source     = "www.somecompany.com";
                        ourId.SourceType = IdSourceTypeEnum.URI;
                        manufacturer.Id.UniqueIds.Add(ourId);
                        manufacturer.Description = appliedProduct["Manufacturer"].ToString();
                        export.Catalog.Manufacturers.Add(manufacturer);
                    }

                    // This is sub-optimal, but it is what we have to work with at the moment.
                    // We're creating the use of each product as its own "operation"
                    OperationSummary operation = new OperationSummary();
                    operation.Data = new List <StampedMeteredValues>();
                    if (appliedProduct["Type"].ToString() == "Seed")
                    {
                        #region Handle Seed
                        CropVariety cropVariety = null;
                        var         products    = export.Catalog.Products.Where(x => (x.Description == appliedProduct["Product"].ToString())).ToList();
                        if (products.Count > 0)
                        {
                            cropVariety = products[0] as CropVariety;
                        }
                        else
                        {
                            cropVariety      = new CropVariety();
                            ourId            = new UniqueId();
                            ourId.Id         = appliedProduct["ProductId"]["Id"].ToString();
                            ourId.IdType     = IdTypeEnum.UUID;
                            ourId.Source     = "www.somecompany.com";
                            ourId.SourceType = IdSourceTypeEnum.URI;
                            cropVariety.Id.UniqueIds.Add(ourId);
                            cropVariety.Description = appliedProduct["Product"].ToString();
                            cropVariety.CropId      = crop.Id.ReferenceId;
                            if (manufacturer != null)
                            {
                                cropVariety.ManufacturerId = manufacturer.Id.ReferenceId;
                            }
                            export.Catalog.Products.Add(cropVariety);
                        }
                        operation.ProductId     = cropVariety.Id.ReferenceId;
                        operation.OperationType = OperationTypeEnum.SowingAndPlanting;
                        #endregion
                    }
                    else if (appliedProduct["Type"].ToString() == "CropProtection")
                    {
                        #region Handle CropProtection
                        CropProtectionProduct cropProtection = null;
                        var products = export.Catalog.Products.Where(x => (x.Description == appliedProduct["Product"].ToString())).ToList();
                        if (products.Count > 0)
                        {
                            cropProtection = products[0] as CropProtectionProduct;
                        }
                        else
                        {
                            cropProtection   = new CropProtectionProduct();
                            ourId            = new UniqueId();
                            ourId.Id         = appliedProduct["ProductId"]["Id"].ToString();
                            ourId.IdType     = IdTypeEnum.UUID;
                            ourId.Source     = "www.somecompany.com";
                            ourId.SourceType = IdSourceTypeEnum.URI;
                            cropProtection.Id.UniqueIds.Add(ourId);
                            cropProtection.Description = appliedProduct["Product"].ToString();
                            if (manufacturer != null)
                            {
                                cropProtection.ManufacturerId = manufacturer.Id.ReferenceId;
                            }
                            if (!string.IsNullOrEmpty(appliedProduct["RegNo"].ToString()))
                            {
                                ContextItem epaNumber = new ContextItem();
                                epaNumber.Code  = "US-EPA-N";
                                epaNumber.Value = ConditionEPA(appliedProduct["RegNo"].ToString(), true, true);
                                cropProtection.ContextItems.Add(epaNumber);
                            }
                            export.Catalog.Products.Add(cropProtection);
                        }
                        operation.ProductId     = cropProtection.Id.ReferenceId;
                        operation.OperationType = OperationTypeEnum.CropProtection;
                        #endregion
                    }
                    else if (appliedProduct["Type"].ToString() == "Fertilizer")
                    {
                        #region Handle Fertilizer
                        FertilizerProduct cropNutrition = null;
                        var products = export.Catalog.Products.Where(x => (x.Description == appliedProduct["Product"].ToString())).ToList();
                        if (products.Count > 0)
                        {
                            cropNutrition = products[0] as FertilizerProduct;
                        }
                        else
                        {
                            cropNutrition    = new FertilizerProduct();
                            ourId            = new UniqueId();
                            ourId.Id         = appliedProduct["ProductId"]["Id"].ToString();
                            ourId.IdType     = IdTypeEnum.UUID;
                            ourId.Source     = "www.somecompany.com";
                            ourId.SourceType = IdSourceTypeEnum.URI;
                            cropNutrition.Id.UniqueIds.Add(ourId);
                            cropNutrition.Description = appliedProduct["Product"].ToString();
                            if (manufacturer != null)
                            {
                                cropNutrition.ManufacturerId = manufacturer.Id.ReferenceId;
                            }
                            export.Catalog.Products.Add(cropNutrition);
                        }
                        operation.ProductId     = cropNutrition.Id.ReferenceId;
                        operation.OperationType = OperationTypeEnum.Fertilizing;
                        #endregion
                    }

                    StampedMeteredValues smv = new StampedMeteredValues();
                    MeteredValue         mv  = null;

                    NumericRepresentationValue rateValue = null;
                    #region Set the product rate (currently hardcoded to be per acre)
                    switch (appliedProduct["RateUnit"].ToString())
                    {
                    case ("seed"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrSeedRateSeedsActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("seeds1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("kernel"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrSeedRateSeedsActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("seeds1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("short ton"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ton1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("metric ton"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("t1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("pound"):
                        if (appliedProduct["Type"].ToString() == "Seed")
                        {
                            rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrSeedRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("lb1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        }
                        else
                        {
                            rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("lb1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        }
                        break;

                    case ("ounce"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("oz1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("kilogram"):
                        if (appliedProduct["Type"].ToString() == "Seed")
                        {
                            rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrSeedRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("kg1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        }
                        else
                        {
                            rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("kg1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        }
                        break;

                    case ("gram"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("g1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("fluid ounce"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("floz1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("quart"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("qt1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("pint"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("pt1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("milliliter"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ml1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("liter"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("l1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("gallon"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("gal1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("centiliter"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("cl1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("acre"):
                        break;

                    default:
                        break;
                    }
                    if (rateValue != null)
                    {
                        mv       = new MeteredValue();
                        mv.Value = rateValue;
                        smv.Values.Add(mv);
                    }
                    #endregion

                    // Set the "applied area" for this use of the product (currently hardcoded to be in acres)
                    NumericRepresentationValue areaValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalAreaCovered.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ac1"), Convert.ToDouble(appliedProduct["AreaApplied"].ToString())));
                    mv       = new MeteredValue();
                    mv.Value = areaValue;
                    smv.Values.Add(mv);

                    if (!string.IsNullOrEmpty(appliedProduct["ApplicationMethod"].ToString()))
                    {
                        EnumeratedValue applicationMethod = null;
                        #region Set the product application method
                        switch (appliedProduct["ApplicationMethod"].ToString())
                        {
                        case ("Aerial"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiAerial.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Air Blast"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiAirBlast.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Chemigation"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiChemigation.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Fertigation"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiFertigation.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Ground - Banded"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiBand.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Ground - Broadcast"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiBroadcast.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Ground - Hooded"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiHoodedSprayer.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Ground - In Furrow"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiInFurrow.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Ground Application"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiInGround.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Planting"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiPlanter.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Re-Planting"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiPlanter.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Sidedress"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiSideDress.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Fumigation"):
                        case ("Ground - Incorporated"):
                        case ("Ground - Seed Treatment"):
                        case ("Ground - Variable Rate"):
                        case ("Storage"):
                        case ("Topdress"):
                        case ("Tree Injection"):
                        case ("Water Run"):
                        default:
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiInGround.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;
                        }
                        if (applicationMethod != null)
                        {
                            mv       = new MeteredValue();
                            mv.Value = applicationMethod;
                            smv.Values.Add(mv);
                        }
                        #endregion
                    }

                    // There is a problem here handling seed totals by bag....will have to come back to this at some point
                    NumericRepresentationValue totalProductValue = null;
                    #region Set the total product
                    switch (appliedProduct["TotalProductUnit"].ToString())
                    {
                    case ("seed"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalSeedQuantityAppliedSeed.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("seeds"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("kernel"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalSeedQuantityAppliedSeed.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("seeds"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("short ton"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ton"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("metric ton"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("t"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("pound"):
                        if (appliedProduct["Type"].ToString() == "Seed")
                        {
                            totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalSeedQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("lb"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        }
                        else
                        {
                            totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("lb"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        }
                        break;

                    case ("ounce"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("oz"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("kilogram"):
                        if (appliedProduct["Type"].ToString() == "Seed")
                        {
                            totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalSeedQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("kg"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        }
                        else
                        {
                            totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("kg"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        }
                        break;

                    case ("gram"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("g1ac-1"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("fluid ounce"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("floz"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("quart"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("qt"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("pint"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("pt"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("milliliter"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ml"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("liter"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("l"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("gallon"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("gal"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("centiliter"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("cl"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("acre"):
                        break;

                    default:
                        break;
                    }
                    if (totalProductValue != null)
                    {
                        mv       = new MeteredValue();
                        mv.Value = totalProductValue;
                        smv.Values.Add(mv);
                    }
                    #endregion

                    operation.Data.Add(smv);

                    // Add the OperationSummary to the collection in Summary
                    summary.OperationSummaries.Add(operation);
                    // End - Foreach Product
                }
                // Add this Summary to the list
                summaries.Add(summary);

                // Add the WorkRecord to the list
                workRecords.Add(workRecord);
                // End - Foreach Application
            }

            // This property is an IEnumerable so we had to build up the collection in a local list then assign it
            export.Documents.Summaries = summaries;
            // This property is an IEnumerable so we had to build up the collection in a local list then assign it
            export.Documents.WorkRecords = workRecords;
            // Make sure the target directory exits
            string outputPath = applicationPath + @"\Output";
            if (Directory.Exists(outputPath))
            {
                Directory.Delete(outputPath, true);
            }
            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }
            admPlugin.Export(export, outputPath);

            // NOTE: There is a fundamental problem with this version of ADAPT 1.1.0.8 and the ADMPlugin that prevents
            // the Summary and WorkRecord objects from serializing correctly. This sample will be updated after the MVP
            // process is complete.
        }
 public void RemoveRecord(WorkRecord record)
 {
     // TO ASK: shall we set a field of the record?
     EnsureEmployeeWithSpecifiedLogin(record.EmployeeDescription.Employee.Login);
     _db.RemoveRecord(record);
 }
Пример #31
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            WorkRecord.DakkaByID((sender as Button).Tag as string);

            MessageBox.Show("OK", "dakka success!");
        }
 public void RemovedRecordIsRemovedPermanently()
 {
     PublicUserInfo userInfo = new PublicUserInfo() { Login = "******" };
     Project project = new Project() { Manager = userInfo };
     EmployeeDescription employeeDescription = new EmployeeDescription() { Employee = userInfo, Project = project };
     WorkRecord workRecord = new WorkRecord() { EmployeeDescription = employeeDescription };
     User user = new User() { PublicUserInfo = userInfo };
     Dao.SetUser(user);
     Dao.SetProject(project);
     Dao.SetEmployeeDescription(employeeDescription);
     Dao.SetRecord(workRecord);
     Assert.IsTrue(Dao.GetRecordsOfEmployee(employeeDescription).Count > 0);
     Dao.RemoveRecord(workRecord);
     Assert.IsFalse(Dao.GetRecordsOfEmployee(employeeDescription).Count > 0);
 }