public async Task <JsonResult> Delete(long id)
        {
            Logger.LogInformation($"Package {id} deleted by {UserSecurity.SamAccountName}");
            await _packageFactory.DeleteSoftwareComponent(id);

            return(Json(JsonEnvelope.Success()));
        }
        public async Task <JsonResult> CleanDuplicates(JustificationTypeConstant id, long specId)
        {
            await _packageFactory.RemoveSoftwareComponentDuplicates(id, specId);

            Logger.LogInformation($"{id} cleaned up by by {UserSecurity.SamAccountName} for specId {specId}");
            return(Json(JsonEnvelope.Success(new { url = Url.PartialGetPackages(id, specId) })));
        }
        public async Task <JsonResult> Assign(long id, long?justificationId)
        {
            Logger.LogInformation($"Package {id} assigned to justification {justificationId} by {UserSecurity.SamAccountName}");
            await _packageFactory.AssignJustification(id, justificationId);

            return(Json(JsonEnvelope.Success()));
        }
Beispiel #4
0
        public async Task <JsonResult> Save(TInfo info)
        {
            if (info == null)
            {
                return(Json(JsonEnvelope.Error("No data passed in to save.")));
            }

            var errors = info.Validate();

            if (errors.Count > 0)
            {
                return(Json(JsonEnvelope.Error(errors)));
            }

            if (!await SpecFactory.IsUnique(info))
            {
                errors.Add("name", "The Specification Name has already been used.  Please change the name and try again.");
                return(Json(JsonEnvelope.Error(errors)));
            }

            await SpecFactory.AddOrUpdate(info);

            LogSave(info);
            return(Json(JsonEnvelope.Success(new { id = info.Id })));
        }
        public JsonResult GetData()
        {
            var model = DependencyResolver.Current.GetService <VpsSliderModel>();

            model.UseSliders = false;
            if (ConfigurationManager.AppSettings["UseSliders"] != null)
            {
                bool useSliders;
                if (Boolean.TryParse(ConfigurationManager.AppSettings["UseSliders"].ToString().ToLower(), out useSliders))
                {
                    model.UseSliders = useSliders;
                }
            }
            if (ConfigurationManager.AppSettings["SliderConfig"] != null)
            {
                model.SliderConfig = ConfigurationManager.AppSettings["SliderConfig"].ToString().Replace("\"", "\\\"");
            }
            model.VpsPriceDecimalPlaces = 4;
            if (ConfigurationManager.AppSettings["VpsPriceDecimalPlaces"] != null)
            {
                int vpsPriceDecimalPrices = 4;
                if (Int32.TryParse(ConfigurationManager.AppSettings["VpsPriceDecimalPlaces"].ToString(), out vpsPriceDecimalPrices))
                {
                    model.VpsPriceDecimalPlaces = vpsPriceDecimalPrices;
                }
            }

            return(JsonEnvelope.Success(model));
        }
        public JsonResult Valdate(string justification, string ports, SimplePortDirectionTypeConstant?direction, PortTypeConstant?portType)
        {
            var errors = new Dictionary <string, string>();
            var ret    = _portFactory.Validate(ports);

            if (!ret.IsValid)
            {
                errors.Add("ports", $"The ports entered were not valid.  The valid configuration is {ret.Ports.ToPortString()}");
            }
            if (!_justificationFactory.IsValidText(justification))
            {
                errors.Add("justification", "The Justifcation cannot be empty whitespace.");
            }

            if (!direction.HasValue)
            {
                errors.Add("direction", "You must choose a direction");
            }

            if (!portType.HasValue)
            {
                errors.Add("portType", "You must choose a type");
            }

            if (errors.Count == 0)
            {
                return(Json(JsonEnvelope.Success()));
            }

            return(Json(JsonEnvelope.Error(errors)));
        }
        /// <summary>
        /// Get single product JSON data from article number.
        /// </summary>
        public JsonResult GetItem(string articleNumber)
        {
            if (ModelState.IsValid)
            {
                Product product = null;

                try
                {
                    product = productProvider.GetProduct(articleNumber);
                }
                catch (ArgumentException)
                {
                }

                if (product != null)
                {
                    return(JsonEnvelope.Success(new
                    {
                        Item = new ProductModel(product)
                    }));
                }
                else
                {
                    return(JsonEnvelope.Fail(new
                    {
                        Message = String.Format("No product with article number {0}", articleNumber)
                    }));
                }
            }

            return(JsonEnvelope.Fail(ModelState));
        }
Beispiel #8
0
        public async Task <JsonResult> ComplianceReport(long id)
        {
            Logger.LogInformation($"Compliance Report Called for {id}");
            await _gatherer.ComplianceReport(id);

            return(Json(JsonEnvelope.Success()));
        }
        public async Task <JsonResult> Save(PlatformConstant id, long specId, long?justificationId, SimplePortDirectionTypeConstant direction, PortTypeConstant portType,
                                            string justification, string ports)
        {
            if (!_justificationFactory.IsValidText(justification))
            {
                return(Json(JsonEnvelope.Error("The Justifcation cannot be empty whitespace.")));
            }

            if (!justificationId.HasValue)
            {
                Logger.LogInformation($"{UserSecurity.SamAccountName} added a new justification for ports: {justification}");
                justificationId =
                    await _justificationFactory.AddJustification(JustificationTypeConstant.Port, specId, justification);
            }
            else
            {
                Logger.LogInformation($"{UserSecurity.SamAccountName} updated justification {justificationId} for ports: {justification}");
                await _justificationFactory.UpdateJustification(justificationId.Value, justification);
            }

            await _portFactory.AddOrUpdatePorts(specId, justificationId.Value, direction == SimplePortDirectionTypeConstant.PortListeningToOutsideTraffic, direction == SimplePortDirectionTypeConstant.SendingTrafficToOusidePort, portType, ports);

            Logger.LogInformation($"{UserSecurity.SamAccountName} added or updated ports for spec {specId} ports are: {ports}");
            return(Json(JsonEnvelope.Success(new { url = Url.PartialOnePort(id, specId, justificationId.Value) })));
        }
        public async Task <JsonResult> Spread()
        {
            var spread = await _dashboardFactory.Spread();

            return(Json(JsonEnvelope.Success(new
            {
                product = new
                {
                    categories = spread.ProductSpecs.Select(p => p.Name).ToArray(),
                    series = new[]
                    {
                        new { name = "# of Specs", data = spread.ProductSpecs.Select(p => p.SpecCount).ToArray() },
                        new { name = "# of Nodes", data = spread.ProductSpecs.Select(p => p.NodeCount).ToArray() },
                    }
                },
                os = new
                {
                    categories = spread.OsSpecs.Select(p => p.Name).ToArray(),
                    series = new[]
                    {
                        new { name = "# of Specs", data = spread.OsSpecs.Select(p => p.SpecCount).ToArray() },
                        new { name = "# of Nodes", data = spread.OsSpecs.Select(p => p.NodeCount).ToArray() },
                    }
                }
            })));
        }
        public async Task <JsonResult> Status()
        {
            var status = await _dashboardFactory.Status();

            return(Json(JsonEnvelope.Success(new
            {
                outOfScope = new[]
                {
                    new{ name = "Appliance", data = new [] { status.Applicance.PciCount, status.Applicance.TotalCount }, lockrType = PlatformConstant.Appliance.ToString(), url = Url.NodeSearch() },
                    new{ name = "UNIX", data = new [] { status.Unix.PciCount, status.Unix.TotalCount }, lockrType = PlatformConstant.Unix.ToString(), url = Url.NodeSearch() },
                    new{ name = "Product", data = new [] { status.ProductExcluded.PciCount, status.ProductExcluded.TotalCount }, lockrType = "", url = Url.NodesExcludedByProductReport() },
                    new{ name = "Other OS", data = new [] { status.OsOther.PciCount, status.OsOther.TotalCount }, lockrType = PlatformConstant.Other.ToString(), url = Url.NodeSearch() },
                },
                failing = new[]
                {
                    new{ name = "Compliance Failure", data = new [] { status.FailingCompliance.PciCount, status.FailingCompliance.TotalCount }, lockrType = Models.Nodes.NodeComplianceSearchTypeConstant.Failing.ToString(), url = Url.NodeSearch() },
                    new{ name = "Not Reporting", data = new [] { status.NotReporting.PciCount, status.NotReporting.TotalCount }, lockrType = Models.Nodes.NodeComplianceSearchTypeConstant.NotReporting.ToString(), url = Url.NodeSearch() },
                    new{ name = "Not Assigned", data = new [] { status.Unassigned.PciCount, status.Unassigned.TotalCount }, lockrType = Models.Nodes.NodeComplianceSearchTypeConstant.Unassigned.ToString(), url = Url.NodeSearch() },
                },
                inScope = new[]
                {
                    new{ type = "pie", name = "PCI", url = Url.NodeSearch(), data = new [] { new { name = "Passing", y = status.Passing.PciCount }, new { name = "Failing", y = status.TotalFailing.PciCount } }, center = new[] { "25%", "50%" }, size = "50%" },
                    new{ type = "pie", name = "All", url = Url.NodeSearch(), data = new [] { new { name = "Passing", y = status.Passing.TotalCount }, new { name = "Failing", y = status.TotalFailing.TotalCount } }, center = new[] { "75%", "50%" }, size = "50%" }
                }
            })));
        }
Beispiel #12
0
        public JsonResult Save(Guid?id, Guid?assignedToId, ActionItemPriorityConstants?priority, DateTime?due, string text)
        {
            var errors = new Dictionary <string, string>();

            if (due == null)
            {
                errors.Add("due", "Due Date is required");
            }

            if (string.IsNullOrWhiteSpace(text))
            {
                errors.Add("text", "Test is required");
            }

            if (assignedToId == null)
            {
                errors.Add("assignedToName", "Assigned to is required");
            }

            if (errors.Count > 0)
            {
                return(Json(JsonEnvelope.Error(errors)));
            }

            _todoService.Save(id, assignedToId.GetValueOrDefault(), priority.GetValueOrDefault(ActionItemPriorityConstants.Normal), due.GetValueOrDefault(), text);
            return(Json(JsonEnvelope.Success()));
        }
        /// <summary>
        /// Deletes a time registration
        /// </summary>
        /// <param name="registrationId"></param>
        /// <returns></returns>
        public ActionResult Delete(string registrationId)
        {
            // Prepare the envelope with a faulty state
            var _result = new JsonEnvelope<bool> { Success = false, Data = false, Message = "No delete" };

            // Execute the delete request
            var _response = SessionHelper.Instance.ProjectManagementClient.DeleteWork(new[] { registrationId }, 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 == 20004 || _response.ErrorCode == 20003)
            {
                // Token not valid anymore.
                FormsAuthentication.SignOut();
                return new JsonResult { Data = new { Error = true, _response.ErrorCode, _response.Messages.FirstOrDefault().Message }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
            else
            {
                return new JsonResult { Data = new { Error = true, _response.ErrorCode, _response.Messages.FirstOrDefault().Message }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }

            // Return the data as JSON
            return new JsonResult { Data = _result, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
        /// <summary>
        /// Gets a list of registrations based on the currently authenticated user
        /// </summary>
        /// <param name="start">Period start date (optional)</param>
        /// <param name="end">Period end date (optional)</param>
        /// <returns>A JsonResult including the work units</returns>
        public ActionResult Get(DateTime? start, DateTime? end)
        {
            // Check if a start date was supplied, otherwise choose today as start
            if (!start.HasValue)
            {
                start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
            }

            // Check if end date was supplied, otherwise use the same as start - to only get one days of registrations back
            if (!end.HasValue)
            {
                end = start.Value;
            }

            // Reset possible time stamps
            var _startDate = new DateTime(start.Value.Year, start.Value.Month, start.Value.Day, 0, 0, 0);
            var _endDate = new DateTime(end.Value.Year, end.Value.Month, end.Value.Day, 0, 0, 0);

            // Create the JSON response envelope, initialize with unsuccessful envelope
            var _result = new JsonEnvelope<IEnumerable<Registration>> { Success = false, Data = new List<Registration>(), Message = "No registrations" };

            // Query the TimeLog Project web service for work units
            var _response = SessionHelper.Instance.ProjectManagementClient.GetEmployeeWork(SessionHelper.Instance.Initials, _startDate, _endDate, SessionHelper.Instance.ProjectManagementToken);

            // Check if the response was correct
            if (_response.ResponseState == ExecutionStatus.Success)
            {
                // Recreate the envelope including the work units from the service
                _result = new JsonEnvelope<IEnumerable<Registration>>
                {
                    Success = true,
                    Data = _response.Return.Select(t => new Registration
                    {
                        Id = t.GUID,
                        Date = t.StartDateTime.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds, // Convert to JavaScript date
                        Hours = t.EndDateTime.Subtract(t.StartDateTime).TotalHours,
                        TaskId = t.Details.TaskHeader.ID,
                        TaskName = t.Details.TaskHeader.FullName,
                        ProjectId = t.Details.ProjectHeader.ID,
                        ProjectName = t.Details.ProjectHeader.Name,
                        Comment = t.Description
                    }),
                    Message = string.Empty
                };
            }
            else if (_response.ErrorCode == 20004 || _response.ErrorCode == 20003)
            {
                // Token not valid anymore.
                FormsAuthentication.SignOut();
                return new JsonResult { Data = new { Error = true, _response.ErrorCode, _response.Messages.FirstOrDefault().Message }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
            else
            {
                return new JsonResult { Data = new { Error = true, _response.ErrorCode, _response.Messages.FirstOrDefault().Message }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }

            // Return the data as JSON
            return new JsonResult { Data = _result, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
 public SignedPayloadViewModel(JsonEnvelope jsonEnvelope)
 {
     Payload   = jsonEnvelope.Payload;
     Signature = jsonEnvelope.Signature;
     PublicKey = jsonEnvelope.PublicKey;
     Encoding  = jsonEnvelope.Encoding;
     Mimetype  = jsonEnvelope.Mimetype;
 }
        public async Task <JsonResult> Delete(long id)
        {
            await _justificationFactory.DeleteJustification(id);

            Logger.LogInformation($"Justification {id} deleted by {UserSecurity.SamAccountName}.");

            return(Json(JsonEnvelope.Success()));
        }
        public async Task <JsonResult> AssignedNodeIds(long id, int?environmentId)
        {
            var nodeIds = await _buildSpecificationFactory.AssignedNodeIds(id, environmentId.GetValueOrDefault());

            var urls = nodeIds.Select(p => Url.JsonComplianceReport(p));

            return(Json(JsonEnvelope.Success(new { urls })));
        }
        public async Task <JsonResult> ChangeColor(long id, string color)
        {
            await _justificationFactory.ChangeColor(id, color);

            Logger.LogInformation($"Justification {id} color updated by {UserSecurity.SamAccountName} to {color}");

            return(Json(JsonEnvelope.Success()));
        }
Beispiel #19
0
 /// <summary>
 /// Get current and available langugages
 /// </summary>
 public JsonResult GetLanguages()
 {
     return(JsonEnvelope.Success(new
     {
         Languages = languageProvider.GetAvailableLanguages(),
         CurrentLanguage = languagePreferenceProvider.GetCurrentLanguage()
     }));
 }
Beispiel #20
0
        public async Task <JsonResult> Products()
        {
            var data = await _scoreCardFactory.GetProductCodes();

            var urls = data.Select(p => Url.PartialProductScoreCard(p));

            return(Json(JsonEnvelope.Success(new { urls })));
        }
        public async Task <JsonResult> Delete(long id)
        {
            Logger.LogInformation($"{UserSecurity.SamAccountName} deleted ports and justification for justification id {id}");
            await _portFactory.DeletePort(id);

            await _justificationFactory.DeleteJustification(id);

            return(Json(JsonEnvelope.Success()));
        }
Beispiel #22
0
        public async Task <JsonResult> GatherForSpec(long id, int environmentId)
        {
            Logger.LogInformation($"Gather Called for {id} and {environmentId}");
            var ids = await _nodeFactory.ChefIdsForAppOrOsSpecAndEnvironment(id, environmentId);

            await _gatherer.Gather(environmentId, ids);

            return(Json(JsonEnvelope.Success()));
        }
        /// <summary>
        /// Get the current cart and domain categories.
        /// </summary>
        public JsonResult GetCart()
        {
            var cart = cartProvider.GetCart();

            return(JsonEnvelope.Success(new
            {
                Cart = new CartModel(cart),
                DomainCategories = domainsProvider.GetDomainCategories()
            }));
        }
 /// <summary>
 /// Gets the currencies.
 /// </summary>
 /// <returns>JSON with the list of available currencies and the current currency.</returns>
 public JsonResult GetCurrencies()
 {
     return
         (JsonEnvelope.Success(
              new
     {
         Currencies = this.currencyProvider.GetAvailableCurrencies(),
         CurrentCurrency = this.currencyPreferenceProvider.GetCurrentCurrency()
     }));
 }
Beispiel #25
0
        public ActionResult ValidateVatNumber(string vatNumber)
        {
            if (!string.IsNullOrEmpty(vatNumber))
            {
                vatDataProvider.VatNumber = vatNumber;
            }

            var result = vatValidator.ValidateCustomerVatNumber();

            return(JsonEnvelope.Success(result));
        }
Beispiel #26
0
        public async Task <JsonResult> Delete(long id)
        {
            string reason = await SpecFactory.Delete(id, UserSecurity);

            if (reason == null)
            {
                LogDelete(id);
                return(Json(JsonEnvelope.Success()));
            }
            return(Json(JsonEnvelope.Error(reason)));
        }
Beispiel #27
0
        public async Task <JsonResult> Clone(long id)
        {
            var newId = await SpecFactory.Clone(id, UserSecurity);

            return(Json(JsonEnvelope.Success(new
            {
                url = BuildSpecificationType == BuildSpecificationTypeConstant.Application
                    ? Url.AppSpecsWizardFromClone(newId)
                    : Url.OsSpecsWizardFromClone(newId)
            })));
        }
        public async Task <JsonResult> Save(long id, string name, string description, bool?nonCore, PciScopeConstant[] pciScope, int[] environmentIds)
        {
            if (!_packageFactory.IsValidName(name))
            {
                return(Json(JsonEnvelope.Error("The Name cannot be empty whitespace.")));
            }

            await _packageFactory.SaveSoftwareComponent(id, name?.Trim(), description?.Trim(), nonCore.GetValueOrDefault(), pciScope, environmentIds);

            Logger.LogInformation($"Software Component {id} updated by {UserSecurity.SamAccountName} with name {name}");
            return(Json(JsonEnvelope.Success(new { url = Url.PartialGetPackage(id) })));
        }
        public async Task <JsonResult> Update(long id, string text)
        {
            if (!_justificationFactory.IsValidText(text))
            {
                return(Json(JsonEnvelope.Error("The Justifcation cannot be empty whitespace.")));
            }

            await _justificationFactory.UpdateJustification(id, text);

            Logger.LogInformation($"Justification {id} updated by {UserSecurity.SamAccountName} with new text: {text}");

            return(Json(JsonEnvelope.Success()));
        }
        public async Task <JsonResult> Add(JustificationTypeConstant id, long specId, string text)
        {
            if (!_justificationFactory.IsValidText(text))
            {
                return(Json(JsonEnvelope.Error("The Justifcation cannot be empty whitespace.")));
            }

            var newid = await _justificationFactory.AddJustification(id, specId, text);

            Logger.LogInformation($"Justification {newid} added by {UserSecurity.SamAccountName} with text: {text}");

            return(Json(JsonEnvelope.Success(new { url = Url.PartialGetJustification(newid) })));
        }
        /// <summary>
        /// 404 Not Found
        /// </summary>
        public ActionResult NotFound(Exception error)
        {
            Response.StatusCode = (int)HttpStatusCode.NotFound;

            if (Request.IsAjaxRequest())
            {
                Response.ContentType = "application/json";
                return(JsonEnvelope.Error("Resource not found."));
            }
            else
            {
                Response.ContentType = "text/html";
                return(View());
            }
        }
        /// <summary>
        /// 500 Internal Server Error
        /// </summary>
        public ActionResult InternalServerError(Exception error)
        {
            Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            if (Request.IsAjaxRequest())
            {
                Response.ContentType = "application/json";
                return(JsonEnvelope.Error("An unknown error has occurred."));
            }
            else
            {
                Response.ContentType = "text/html";
                return(View());
            }
        }
Beispiel #33
0
        /// <summary>
        /// Gets a list of tasks allocated to the currently authenticated user
        /// </summary>
        /// <returns>A JsonResult with tasks</returns>
        public ActionResult Get()
        {
            // Prepare the envelope with a faulty state
            var _result = new JsonEnvelope<IEnumerable<Task>> { Success = false, Data = new List<Task>(), Message = "No tasks" };

            // Query the TimeLog Project web service for tasks allocated to the employee
            var _tasksResponse = SessionHelper.Instance.ProjectManagementClient.GetTasksAllocatedToEmployee(SessionHelper.Instance.Initials, SessionHelper.Instance.ProjectManagementToken);

            // Check if the state is correct
            if (_tasksResponse.ResponseState == TimelogProjectManagement.ExecutionStatus.Success)
            {
                // Recreate the result including the task data
                _result = new JsonEnvelope<IEnumerable<Task>>
                {
                    Success = true,
                    Data = _tasksResponse.Return.Where(t => !t.IsParent).Select(t => new Task
                    {
                        Id = t.ID,
                        Name = t.FullName,
                        ProjectId = t.Details.ProjectHeader.ID,
                        ProjectName = t.Details.ProjectHeader.Name
                    }),
                    Message = string.Empty
                };
            }
            else if (_tasksResponse.ErrorCode == 20004 || _tasksResponse.ErrorCode == 20003)
            {
                // Token not valid anymore.
                FormsAuthentication.SignOut();
                return new JsonResult { Data = new { Error = true, _tasksResponse.ErrorCode, _tasksResponse.Messages.FirstOrDefault().Message }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
            else
            {
                return new JsonResult { Data = new { Error = true, _tasksResponse.ErrorCode, _tasksResponse.Messages.FirstOrDefault().Message }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }

            // Return the data as JSON
            return new JsonResult { Data = _result, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
        /// <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 };
        }