Beispiel #1
0
        private bool CheckForUnapprovedEntries(DBDocument allocationEntry)
        {
            logger.LogTrace("Checking whether allocation has unapproved entries");

            bool hasUnapprovedEntries = false;

            var query = new DBQuery("homescreenprojects", "unapprovedentriesforproject");

            query.AddParameter("project", allocationEntry["project"]);
            query.AddParameter("user", allocationEntry["user"]);

            DBResponse response = query.Find();


            if (response["timesheetentry"].Count > 0)
            {
                hasUnapprovedEntries = true;
            }
            else if (response["absenceentry"].Count > 0)
            {
                hasUnapprovedEntries = true;
            }
            else if (response["dayentry"].Count > 0)
            {
                hasUnapprovedEntries = true;
            }
            else if (response["articleentry"].Count > 0)
            {
                hasUnapprovedEntries = true;
            }
            return(hasUnapprovedEntries);
        }
Beispiel #2
0
        public ActionResult endworkonproject(string allocationid)
        {
            logger.LogTrace("Ending work on allocation", allocationid);

            if (string.IsNullOrEmpty(allocationid))
            {
                return(new AjaxResult("Allocation id missing. Cannot end work."));

                logger.LogError("Allocation id missing. Cannot end work.");
            }

            var allocationEntry = DBDocument.FindOne("allocationentry", allocationid);

            try
            {
                if ((bool)Runtime.Features["onlycompleteapprovedallocations"] && CheckForUnapprovedEntries(allocationEntry))
                {
                    logger.LogDebug("Cannot mark allocation as completed. Not all related entries were worker approved.");
                    return(new AjaxResult("unapprovedentriesfound"));
                }
            }
            catch (Exception)
            {
                // It's likely best to allow completing allocations in case there's an issue.
                logger.LogError("Failed to check whether allocation has unapproved entries. Allowing completion.");
            }

            allocationEntry["status"] = "Done";

            allocationEntry.UpdateDatabase();

            return(new AjaxResult("success"));
        }
Beispiel #3
0
        public Guid AddDocument(DBDocument doc)
        {
            DBDocument d = GetDocumentByURL(doc.URL);
            if (d!=null)
            {
                //doc.ID = d.ID;
                //doc.Versions.Add(d.LastVersion);
                foreach (DBDocumentVersion v in doc.Versions)
                {
                    Guid id = AddDocumentVersion(d.ID, v);
                }
                doc = d;
            }
            else
            {
                command.CommandText = "insert into DOCUMENT ( DC_ID ,  DC_URL   )"+
                    "values ( @DC_ID  , @DC_URL  )";
                command.Parameters.Clear();
                command.Parameters.AddWithValue("DC_ID", doc.ID);
                //command.Parameters.AddWithValue("DC_TYPE", doc.DocType);
                command.Parameters.AddWithValue("DC_URL", doc.URL);
                //command.Parameters.AddWithValue("DC_TITLE", "");
                string q = GetSQL(command);

                int did = command.ExecuteNonQuery();

                foreach (DBDocumentVersion v in doc.Versions)
                {
                    Guid id = AddDocumentVersion(doc.ID, v);
                }
            }
            return doc.ID;
        }
Beispiel #4
0
        public MC2Value trotimesheetduration(DataTree itemSchema)
        {
            MC2Value value = null;

            if (Runtime.CurrentActionCall.Parameters.Contains("relationid"))
            {
                var timesheetQuery = new DBQuery();

                var timesheet = DBDocument.FindOne(
                    new DBCallProperties()
                {
                    DisableEventFiring = true
                },
                    "timesheetentry",
                    Runtime.CurrentActionCall.Parameters["relationid"]);

                TimeSpan durationSpan = ((DateTime)timesheet["endtimestamp"]) - ((DateTime)timesheet["starttimestamp"]);

                value = (int)durationSpan.TotalMilliseconds;
            }
            else
            {
                value = 0;
            }

            return(null);
        }
Beispiel #5
0
        public ActionResult mobiledocuments(string projectid)
        {
            var project = DBDocument.FindOne("project", projectid);

            project["projectmanager"].Merge(DBDocument.FindOne("user", project["projectmanager"][DBDocument.Id]));
            project["customer"].Merge(DBDocument.FindOne("customer", project["customer"][DBDocument.Id]));
            project["currentuser"].Merge(Runtime.SessionManager.CurrentUser);
            //Runtime.SessionManager.CurrentUser
            string json = project.ToJson();

            var request = (HttpWebRequest)WebRequest.Create(Runtime.Config["application"]["mobiledocumentsaddress"]);

            var postData = "project=" + json;
            var data     = Encoding.UTF8.GetBytes(postData);

            request.Method        = "POST";
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            return(new RedirectResult(responseString));
        }
Beispiel #6
0
        internal static void UpdateManager(int documentId, int managerId, bool checkAccess)
        {
            if (checkAccess)
            {
                VerifyCanUpdate(documentId);
            }

            int oldManagerId = DBDocument.GetManager(documentId);

            if (oldManagerId != managerId)
            {
                using (DbTransaction tran = DbTransaction.Begin())
                {
                    DbDocument2.UpdateManager(documentId, managerId);

                    // TODO: implement Document_Updated_Manager
                    // SystemEvents.AddSystemEvents(SystemEventTypes.Document_Updated_Manager, documentId);

                    // OZ: User Role Addon
                    if (managerId != oldManagerId)
                    {
                        UserRoleHelper.DeleteDocumentManagerRole(documentId, oldManagerId);
                        UserRoleHelper.AddDocumentManagerRole(documentId, managerId);
                    }
                    // end OZ

                    tran.Commit();
                }
            }
        }
Beispiel #7
0
        public ActionResult startworkonproject(string projectid)
        {
            if (!string.IsNullOrEmpty(projectid))
            {
                // When starting work first look for existing allocation without date. If we have one we should
                // start that allocation instead of generating a new one.
                var existingAllocationQuery = new DBQuery("startproject", "unscheduledallocation");
                existingAllocationQuery.AddParameter("user", new ObjectId(Runtime.SessionManager.CurrentUser["_id"]));
                existingAllocationQuery.AddParameter("project", new ObjectId(projectid));

                DBDocument allocationEntry = existingAllocationQuery.FindOne();

                if (allocationEntry == null)
                {
                    allocationEntry = new DBDocument("allocationentry");
                }

                allocationEntry.AddRelation("project", projectid);
                allocationEntry.AddRelation("user", Runtime.SessionManager.CurrentUser["_id"]);
                allocationEntry["status"] = "In progress";

                allocationEntry.UpdateDatabaseAsync();

                return(new AjaxResult("success"));
            }
            else
            {
                return(new AjaxResult("No identifier provided. Cannot start work."));
            }
        }
Beispiel #8
0
        //public Extras.Common.Method.ListUtilClass ListUpdRC = null;

        //private Validation _vd;
        //public Validation VD
        //{
        //    get { return _vd; }
        //    set { _vd = value; }
        //}

        public XMLGeneration(MainSettings MSI, Validation VDI)
        {
            MS       = MSI;
            VD       = VDI;
            Document = new DBDocument();
            //ListUpdRC = new Extras.Common.Method.ListUtilClass();
        }
Beispiel #9
0
        private AjaxResult GetDocumentFromDB(
            string collection,
            string id)
        {
            if (string.IsNullOrEmpty(collection))
            {
                return(new AjaxResult("error:Collection not provided when getting document.", HttpStatusCode.NotFound));
            }

            if (string.IsNullOrEmpty(id))
            {
                return(new AjaxResult("error:Identifier not provided when getting document.", HttpStatusCode.NotFound));
            }

            if (!Runtime.Schema.First.Contains(collection))
            {
                return(new AjaxResult("error:Collection not found", HttpStatusCode.NotFound));
            }

            DataTree schema = Runtime.Schema.First[collection];

            DataTree result = DBDocument.FindOne(collection, id);

            if (result == null)
            {
                return(new AjaxResult("error:Document not found", HttpStatusCode.NotFound));
            }

            if (!result.Empty)
            {
                DBQueryHelpers.TidyUpResult(schema, result, Runtime);
            }

            return(new AjaxResult(result));
        }
Beispiel #10
0
        private static bool AddFavouriteUsersFilter(
            string collection,
            string favouriteusersfilter,
            List <IMongoQuery> timesheetEntryAndQueries,
            bool hasFilters = false)
        {
            if (string.IsNullOrEmpty(favouriteusersfilter))
            {
                return(hasFilters);
            }

            DBDocument favouriteUsersDocument = DBDocument.FindOne("favouriteusers", favouriteusersfilter);

            // Fetch all
            if (favouriteUsersDocument != null)
            {
                var favouriteUserOrQueries = new List <IMongoQuery>();

                foreach (DataTree user in favouriteUsersDocument["user"])
                {
                    if (user.Contains(DBQuery.Id))
                    {
                        favouriteUserOrQueries.Add(Query.EQ("user", new ObjectId(user[DBQuery.Id])));
                    }
                }

                timesheetEntryAndQueries.Add(Query.Or(favouriteUserOrQueries));
                hasFilters = true;
            }

            return(hasFilters);
        }
Beispiel #11
0
        public ActionResult getstatus()
        {
            var monitorQuery = new DBQuery();

            monitorQuery["monitorinfo"][DBQuery.Condition] = DBQuery.All;

            string result = "";

            try
            {
                DBDocument resultDoc = monitorQuery.FindOne(new DBCallProperties()
                {
                    RunWithPrivileges = 5
                });

                if (resultDoc == null)
                {
                    return(new AjaxResult("ERROR. No result document found. To configure monitoring add monitorinfo collection to schema and insert one document with the desired response."));
                }

                result = resultDoc["info"];
            }
            catch (Exception ex)
            {
                result = "error: " + ex;
            }

            return(new AjaxResult(result));
        }
Beispiel #12
0
        public AjaxResult unallocate(
            string allocationentry)
        {
            var timesheetToRemoveQuery = new DBDocument("allocationentry", allocationentry);

            timesheetToRemoveQuery.RemoveFromDatabase();

            return(new AjaxResult("success"));
        }
Beispiel #13
0
        private async Task <bool> CopyEntriesToDay(DBCollection collection, DateTime targetDay)
        {
            if (collection.Count == 0)
            {
                return(false);
            }

            var newCollection = new DBCollection(new DataTree(collection.Name));

            var somethingFiltered = false;

            foreach (DBDocument doc in collection)
            {
                // Remove id to make as new
                doc[DBDocument.Id].Remove();

                // Remove timestamps, they will be applied automatically based on date
                doc["starttimestamp"].Remove();
                doc["endtimestamp"].Remove();

                // Remove approval and export data. All pasted entries must be approved again.
                doc["approvedbymanager"]     = false;
                doc["approvedbyworker"]      = false;
                doc["exported_ax"]           = false;
                doc["exportfailurecount_ax"] = 0;
                doc["exporttimestamp_ax"].Remove();
                doc["exported_visma"] = false;
                doc["exporttimestamp_visma"].Remove();

                // Set target date
                doc["date"] = targetDay;

                bool filtered = false;
                if (!doc["project"].Empty)
                {
                    var project = DBDocument.FindOne("project", doc["project"][DBDocument.Id]);
                    if (project != null && project["status"] == "Done")
                    {
                        filtered          = true;
                        somethingFiltered = true;
                    }
                }


                if (!filtered)
                {
                    newCollection.Add(doc);
                }
            }

            await newCollection.UpdateDatabaseAsync(new DBCallProperties()
            {
                RunWithPrivileges = 5
            });

            return(somethingFiltered);
        }
Beispiel #14
0
        public ActionResult addnewlocation(string name)
        {
            var location = new DBDocument("location");

            location["name"] = name;

            location.UpdateDatabase();

            return(new AjaxResult((string)location["_id"]));
        }
Beispiel #15
0
        /// <summary>
        ///		ItemId, ItemName, Weight, StateId, CanDelete (int)
        /// </summary>
        public static DataTable GetList(DictionaryTypes dict)
        {
            DataTable dt = null;

            switch (dict)
            {
            case DictionaryTypes.Categories:
                dt = DBCommon.GetListCategoriesForDictionaries();
                break;

            case DictionaryTypes.IncidentSeverities:
                dt = DBIncident.GetListIncidentSeverityForDictionaries();
                break;

            case DictionaryTypes.IncidentTypes:
                dt = DBIncident.GetListIncidentTypesForDictionaries();
                break;

            case DictionaryTypes.ProjectTypes:
                dt = DBProject.GetListProjectTypesForDictionaries();
                break;

            case DictionaryTypes.ProjectCategories:
                dt = DBProject.GetListProjectCategoriesForDictionaries();
                break;

            case DictionaryTypes.IncidentCategories:
                dt = DBIncident.GetListIncidentCategoriesForDictionaries();
                break;

            case DictionaryTypes.Currency:
                dt = DBCommon.GetListCurrencyForDictionaries();
                break;

            case DictionaryTypes.DocumentStatus:
                dt = DBDocument.GetListDocumentStatusForDictionaries(Security.CurrentUser.LanguageId);
                break;

            case DictionaryTypes.ProjectPhases:
                dt = DBProject.GetListProjectPhasesForDictionaries();
                break;

            case DictionaryTypes.RiskLevels:
                dt = DBProject.GetListRiskLevelsForDictionaries();
                break;
            }

            if (dict != DictionaryTypes.ProjectPhases && dict != DictionaryTypes.RiskLevels && dt != null)
            {
                dt.Columns.Add("Weight", typeof(int));
            }

            return(dt);
        }
Beispiel #16
0
        public ActionResult setuserdata(string key, string value)
        {
            var userdata = new DBDocument("userdata");

            userdata["user"]  = Runtime.SessionManager.CurrentUser["_id"];
            userdata["key"]   = key;
            userdata["value"] = value;

            userdata.UpdateDatabase();

            return(new AjaxResult(""));
        }
Beispiel #17
0
        public static void AddItem(string ItemName, int Param, DictionaryTypes dict)
        {
            if (!Company.CheckDiskSpace())
            {
                throw new MaxDiskSpaceException();
            }

            switch (dict)
            {
            case DictionaryTypes.Categories:
                DBCommon.AddCategory(ItemName);
                break;

            case DictionaryTypes.IncidentSeverities:
                DBIncident.AddIncidentSeverity(ItemName);
                break;

            case DictionaryTypes.IncidentTypes:
                DBIncident.AddIncidentType(ItemName);
                break;

            case DictionaryTypes.ProjectTypes:
                AddProjectType(ItemName);
                break;

            case DictionaryTypes.ProjectCategories:
                DBProject.AddProjectCategory(ItemName);
                break;

            case DictionaryTypes.IncidentCategories:
                DBIncident.AddIncidentCategory(ItemName);
                break;

            case DictionaryTypes.Currency:
                DBCommon.AddCurrency(ItemName);
                break;

            case DictionaryTypes.DocumentStatus:
                DBDocument.AddDocumentStatus(ItemName, Param);
                break;

            case DictionaryTypes.ProjectPhases:
                DBProject.AddProjectPhase(ItemName, Param);
                break;

            case DictionaryTypes.RiskLevels:
                DBProject.AddRiskLevel(ItemName, Param);
                break;
            }
        }
Beispiel #18
0
        public AjaxResult allocateasset(
            string asset,
            string project,
            DateTime start,
            DateTime end,
            string status,
            bool ignoreconflicts = false)
        {
            // Get allocations for given date
            string resultValue = "success";

            bool confilictingAllocationFound = false;

            if (!ignoreconflicts)
            {
                DBQuery query = new DBQuery("dailyresourcingwidget", "getassetallocation");
                query.AddParameter("asset", new ObjectId(asset));
                query.AddParameter("start", start);
                query.AddParameter("end", end);

                DBResponse result = query.FindAsync(new DBCallProperties()
                {
                    RunWithPrivileges = 5
                }).Result;

                if (result["allocationentry"].Count > 0)
                {
                    confilictingAllocationFound = true;
                }
            }

            if (confilictingAllocationFound)
            {
                resultValue = "conflict";
            }
            else
            {
                var newAllocation = new DBDocument("allocationentry");
                newAllocation.AddRelation("asset", asset);
                newAllocation.AddRelation("project", project);

                newAllocation["starttimestamp"] = start;
                newAllocation["endtimestamp"]   = end;

                newAllocation.UpdateDatabase();
            }

            return(new AjaxResult(resultValue));
        }
Beispiel #19
0
        public DocForm(DBDocument aDoc)
        {
            InitializeComponent();
            wbViewer.ScriptErrorsSuppressed = true;
            doc = aDoc;

            this.Text = string.Format("{0} [{1}]",doc.URL, doc.ID.ToString());
            tnVersions.Nodes.Clear();
            TreeNode rn = tnVersions.Nodes.Add(doc.ID.ToString(),"Versions["+doc.Versions.Count.ToString()+"]");
            foreach (DBDocumentVersion v in doc.Versions)
            {
                rn.Nodes.Add(v.ID.ToString(), v.Date.ToString());
            }
            rn.ExpandAll();
        }
Beispiel #20
0
        public static void DeleteItem(int ItemId, DictionaryTypes dict)
        {
            switch (dict)
            {
            case DictionaryTypes.Categories:
                DBCommon.DeleteCategory(ItemId);
                break;

            case DictionaryTypes.IncidentSeverities:
                DBIncident.DeleteIncidentSeverity(ItemId);
                break;

            case DictionaryTypes.IncidentTypes:
                DBIncident.DeleteIncidentType(ItemId);
                break;

            case DictionaryTypes.ProjectTypes:
                DeleteProjectType(ItemId);
                break;

//				case DictionaryTypes.Clients:
//					DBProject.DeleteClient(ItemId);
//					break;
            case DictionaryTypes.ProjectCategories:
                DBProject.DeleteProjectCategory(ItemId);
                break;

            case DictionaryTypes.IncidentCategories:
                DBIncident.DeleteIncidentCategory(ItemId);
                break;

            case DictionaryTypes.Currency:
                DBCommon.DeleteCurrency(ItemId);
                break;

            case DictionaryTypes.DocumentStatus:
                DBDocument.DeleteDocumentStatus(ItemId);
                break;

            case DictionaryTypes.ProjectPhases:
                DBProject.DeleteProjectPhase(ItemId);
                break;

            case DictionaryTypes.RiskLevels:
                DBProject.DeleteRiskLevel(ItemId);
                break;
            }
        }
Beispiel #21
0
        public static void UpdateItem(int ItemId, string ItemName, int Param, DictionaryTypes dict)
        {
            switch (dict)
            {
            case DictionaryTypes.Categories:
                DBCommon.UpdateCategory(ItemId, ItemName);
                break;

            case DictionaryTypes.IncidentSeverities:
                DBIncident.UpdateIncidentSeverity(ItemId, ItemName);
                break;

            case DictionaryTypes.IncidentTypes:
                DBIncident.UpdateIncidentType(ItemId, ItemName);
                break;

            case DictionaryTypes.ProjectTypes:
                UpdateProjectType(ItemId, ItemName);
                break;

//				case DictionaryTypes.Clients:
//					DBProject.UpdateClient(ItemId, ItemName);
//					break;
            case DictionaryTypes.ProjectCategories:
                DBProject.UpdateProjectCategory(ItemId, ItemName);
                break;

            case DictionaryTypes.IncidentCategories:
                DBIncident.UpdateIncidentCategory(ItemId, ItemName);
                break;

            case DictionaryTypes.Currency:
                DBCommon.UpdateCurrency(ItemId, ItemName);
                break;

            case DictionaryTypes.DocumentStatus:
                DBDocument.UpdateDocumentStatus(ItemId, ItemName, Param);
                break;

            case DictionaryTypes.ProjectPhases:
                DBProject.UpdateProjectPhase(ItemId, ItemName, Param);
                break;

            case DictionaryTypes.RiskLevels:
                DBProject.UpdateRiskLevel(ItemId, ItemName, Param);
                break;
            }
        }
Beispiel #22
0
        private string VerifyUser(DBDocument document, DataTree userTotals)
        {
            string userId = document["user"];

            if (string.IsNullOrEmpty(userId))
            {
                return(null);
            }

            if (!userTotals.Contains(userId))
            {
                userTotals[userId]["__displayname"] = document["user"]["__displayname"];
            }

            return(userId);
        }
Beispiel #23
0
        public ActionResult startworkonproject(string projectid, string allocationid)
        {
            if (!string.IsNullOrEmpty(allocationid))
            {
                DBDocument allocationEntry = DBDocument.FindOne("allocationentry", allocationid);

                allocationEntry["status"] = "In progress";

                allocationEntry.UpdateDatabase();

                return(new AjaxResult("success"));
            }
            else
            {
                return(new AjaxResult("No identifier provided. Cannot start work."));
            }
        }
Beispiel #24
0
        /// <summary>
        /// 更新表字段的说明
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        private bool UpdateFieldDescription(DBDocument doc)
        {
            using (var context = new EFDocumentContext())
            {
                string sql = @" DECLARE @CurrentUser SYSNAME
                                SELECT  @CurrentUser = USER_NAME()
                               
                                IF EXISTS ( SELECT  1
                                            FROM    sys.extended_properties p
                                            WHERE   p.major_id = OBJECT_ID(@TableName)
                                                    AND p.minor_id = ( SELECT   c.column_id
                                                                       FROM     sys.columns c
                                                                       WHERE    c.object_id = p.major_id
                                                                                AND c.name = @FiledName
                                                                     ) )  
                                BEGIN
	                                -- 删除说明
                                    EXECUTE sp_dropextendedproperty 'MS_Description', 'user', @CurrentUser,
                                        'table', @TableName, 'column', @FiledName
                                END

                                -- 添加说明
                                EXECUTE sp_addextendedproperty 'MS_Description', @Description, 'user',
                                    @CurrentUser, 'table', @TableName, 'column', @FiledName";

                return(context.Database.ExecuteSqlCommand(sql,
                                                          new SqlParameter
                {
                    ParameterName = "@TableName",
                    DbType = System.Data.DbType.String,
                    Value = doc.TableName
                },
                                                          new SqlParameter
                {
                    ParameterName = "@FiledName",
                    DbType = System.Data.DbType.String,
                    Value = doc.FieldName
                },
                                                          new SqlParameter
                {
                    ParameterName = "@Description",
                    DbType = System.Data.DbType.String,
                    Value = doc.Description ?? string.Empty
                }) > 0);
            }
        }
Beispiel #25
0
        public ActionResult getEntryData(DateTime start, DateTime end)
        {
            var entriesQuery = new DBQuery("workdatawidget", "entrydata");

            entriesQuery.AddParameter("user", Runtime.SessionManager.CurrentUser[DBQuery.Id]);
            entriesQuery.AddParameter("start", start);
            entriesQuery.AddParameter("end", end);

            DBResponse response    = entriesQuery.Find();
            var        allocations = response["allocationentry"];

            foreach (DBDocument allocation in allocations)
            {
                allocation["project"] = DBDocument.FindOne("project", allocation["project"][DBDocument.Id]);
            }

            return(new AjaxResult((DataTree)response));
        }
Beispiel #26
0
        public MC2Value timesheetentryuser(DataTree itemSchema)
        {
            if (Runtime.CurrentActionCall.Parameters["relation"] == "parent")
            {
                string parentId = Runtime.CurrentActionCall.Parameters["relationid"];

                DBDocument parentEntry = DBDocument.FindOne("timesheetentry", parentId);

                if (parentEntry != null && parentEntry["user"][DBQuery.Id].Exists)
                {
                    DBDocument parentUser = DBDocument.FindOne("user", parentEntry["user"][DBQuery.Id]);
                    return(parentUser);
                }
            }

            // Use current user in normal case
            return(Runtime.SessionManager.CurrentUser);
        }
Beispiel #27
0
        public AjaxResult doc(string collection, string id, string placeholder1)
        {
            try
            {
                var document = new DBDocument(collection, id);
                document.RemoveFromDatabase();

                // Todo: handle error response

                return(new AjaxResult("success", HttpStatusCode.NoContent));
            }
            catch (RuntimeException ex)
            {
                return(HandleRuntimeException(ex));
            }
            catch (Exception ex)
            {
                return(HandleGeneralException(ex));
            }
        }
Beispiel #28
0
        public ActionResult editdetail(string id, string paytype, int duration = 0, int price = 0)
        {
            if (string.IsNullOrEmpty("id"))
            {
                return(new AjaxResult("Missing id when editing detail", System.Net.HttpStatusCode.InternalServerError));
            }

            if (string.IsNullOrEmpty("paytype"))
            {
                return(new AjaxResult("Missing paytype when editing detail", System.Net.HttpStatusCode.InternalServerError));
            }

            if (duration == 0 && price == 0)
            {
                return(new AjaxResult("Missing duration and price when editing detail", System.Net.HttpStatusCode.InternalServerError));
            }

            DBDocument detail = DBDocument.FindOne("timesheetentry", id);

            if (detail == null)
            {
                return(new AjaxResult("Could not find detail when editing detail", System.Net.HttpStatusCode.InternalServerError));
            }

            if (duration != 0)
            {
                detail["duration"] = duration;
            }

            if (price != 0)
            {
                detail["price"] = price;
            }

            detail.AddRelation("timesheetentrydetailpaytype", paytype);

            detail.UpdateDatabase();

            // Todo: handle errors
            return(new AjaxResult("success"));
        }
Beispiel #29
0
        public MC2Value trocurrentproject(DataTree itemSchema)
        {
            MC2Value value = null;

            if ((bool)Runtime.CurrentActionCall.Parameters["socialproject"] == true && (bool)Runtime.Config["application"]["features"]["enablesocialproject"])
            {
                // Todo: cache value?
                if (socialProject == null)
                {
                    socialProject = new DBQuery("tro", "getsocialproject").FindOneAsync().Result;
                }

                value = socialProject;
            }
            else if ((bool)Runtime.CurrentActionCall.Parameters["fromhomescreen"] == true)
            {
                // Use either provided project from url or user's project
                if (Runtime.CurrentActionCall.Parameters["workscheduleprojectid"].Exists)
                {
                    value = DBDocument.FindOne("project", Runtime.CurrentActionCall.Parameters["workscheduleprojectid"]);
                }
                else
                {
                    var userQuery = new DBQuery();

                    userQuery["user"][DBQuery.Condition] = Query.EQ(DBQuery.Id, new ObjectId(Runtime.SessionManager.CurrentUser["_id"]))
                                                           .ToString();

                    DataTree currentUser = userQuery.FindOne();

                    value = currentUser["currentproject"];
                }
            }
            else
            {
                value = MC2EmptyValue.EmptyValue;
            }

            return(value);
        }
Beispiel #30
0
        public ActionResult export(
            string payrollperiod,
            string user   = null,
            string target = ExporTargetCsv,
            bool onlyentriesnotacceptedbymanager = false,
            bool onlyentriesnotacceptedbyworker  = false,
            bool onlyexportedentries             = false)
        {
            logger.LogInfo("Received a request to export data", target, payrollperiod, user);

            if (string.IsNullOrEmpty(payrollperiod) && string.IsNullOrEmpty(user))
            {
                logger.LogError("Payroll and user are missing from payroll export request");
                return(new AjaxResult("error: No payroll or user period specified."));
            }

            var export = new DBDocument("payrollexport");

            export["status"] = "WaitingToStart";
            export["target"] = target;
            export["user"]   = user;
            export["onlyentriesnotacceptedbymanager"] = onlyentriesnotacceptedbymanager;
            export["onlyentriesnotacceptedbyworker"]  = onlyentriesnotacceptedbyworker;
            export["onlyexportedentries"]             = onlyexportedentries;

            if (!string.IsNullOrEmpty(payrollperiod))
            {
                export["payrollperiod"] = payrollperiod;
            }

            if (!string.IsNullOrEmpty(user))
            {
                export["user"] = user;
            }

            export.UpdateDatabaseAsync();

            return(new AjaxResult(""));
        }
Beispiel #31
0
        private void UpdatePayTypesIfNeeded()
        {
            if (payTypeUpdateStopwatch.Elapsed.Minutes > PayTypeUpdateIntervalMinutes ||
                expenseTypes == null || payTypes == null)
            {
                var query  = new DBQuery("totalwork", "paytypes");
                var result = query.Find();

                lock (payTypeLock)
                {
                    payTypes     = result["timesheetentrydetailpaytype"];
                    expenseTypes = result["dayentrytype"];

                    if (result["socialproject"].Count >= 0)
                    {
                        socialProject = result["socialproject"][0];
                    }
                }

                payTypeUpdateStopwatch.Restart();
            }
        }
Beispiel #32
0
        public ActionResult adddetail(string parent, string paytype, int duration = 0, int price = 0)
        {
            if (string.IsNullOrEmpty("parent"))
            {
                return(new AjaxResult("Missing parent when adding detail", System.Net.HttpStatusCode.InternalServerError));
            }

            if (string.IsNullOrEmpty("paytype"))
            {
                return(new AjaxResult("Missing paytype when adding detail", System.Net.HttpStatusCode.InternalServerError));
            }

            if (duration == 0 && price == 0)
            {
                return(new AjaxResult("Missing duration and price when adding detail", System.Net.HttpStatusCode.InternalServerError));
            }

            DBDocument detail = new DBDocument("timesheetentry");

            if (duration != 0)
            {
                detail["duration"] = duration;
            }

            if (price != 0)
            {
                detail["price"] = price;
            }

            detail.AddRelation("user", Runtime.SessionManager.CurrentUser[DBQuery.Id]);
            detail.AddRelation("timesheetentrydetailpaytype", paytype);
            detail.AddRelation("parent", parent);

            detail.UpdateDatabase();

            // Todo: handle errors
            return(new AjaxResult("success"));
        }
Beispiel #33
0
        public string PrepareTaggedText(DBDocument d)
        {
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(d.Text);
            StringBuilder docBody = new StringBuilder();
            docBody.Append("\r\n~mainHeader_" + d.LastVersion.Metadata.Title);
            docBody.Append("\r\n~author_" + d.LastVersion.Metadata.Author);
            docBody.Append("\r\n~keywords_" + d.LastVersion.Metadata.KeyWordsString);
            docBody.Append("\r\n~fileName_" + d.FileName);
            docBody.Append("\r\n~fileDate_" + d.Date.ToString());
            docBody.Append("\r\n~codification_" + d.LastVersion.Metadata.Charset);
            docBody.Append("\r\n~content_" + HTMLUtils.GetPlainText(d.Text));

            return docBody.ToString();
        }
Beispiel #34
0
        public DBDocument GetDocumentByField(string field , string value )
        {
            DBDocument doc = null;

            command.CommandText = "select * from DOCUMENT where ("+ field + " = @" + field + ")";
            command.Parameters.Clear();
            command.Parameters.AddWithValue(field, value);
            string q = GetSQL(command);
            SqlDataReader dr = command.ExecuteReader();
            try
            {
                if (dr.HasRows)
                {
                    if (dr.Read())
                    {
                        doc = new DBDocument(this);
                        doc.URL = dr["DC_URL"].ToString();
                        doc.ID = new Guid(dr["DC_ID"].ToString());
                    }
                }
            }
            finally { dr.Close(); }
            if ((doc != null)&&(doc.ID != Guid.Empty))
            {
                command.CommandText = "select * from DOCUMENTDATA where DD_DOCID = @DD_DOCID";
                command.Parameters.Clear();
                command.Parameters.AddWithValue("DD_DOCID", doc.ID);
                 q = GetSQL(command);
                dr = command.ExecuteReader(CommandBehavior.SequentialAccess);
                try
                {
                    if (dr.HasRows)
                        while (dr.Read())
                        {
                            DBDocumentVersion dv = new DBDocumentVersion();
                            dv.ID = new Guid(dr["DD_ID"].ToString());
                            dv.DocID = new Guid(dr["DD_DOCID"].ToString());
                            //dv.ID = new Guid(dr.GetString(dr.GetOrdinal("DD_ID")));
                            dv.Version = int.Parse(dr["DD_VERSION"].ToString());
                            dv.Date = DateTime.Parse(dr["DD_DATE"].ToString());
                            int bufferSize = 10000;
                            dv.Data = new byte[bufferSize];
                            int colnum = dr.GetOrdinal("DD_BODY");
                            //dv.Data = (byte[])dr.GetValue(colnum);
                            dr.GetBytes(colnum, 0, dv.Data, 0, bufferSize);
                            //dr.GetBytes(colnum,)
                            //dv.Data = (byte[])dr["DD_BODY"];
                            dv.ResponseHeader = BytesToUTF8Str((byte[])dr["DD_METADATA"]);
                            doc.Versions.Add(dv);
                        }
                    else
                    {
                        //throw new Exception(string.Format("Versions for Document '{0}' not found", value));
                    }
                }
                finally
                {
                    dr.Close();
                }
            }
            return doc;
        }
Beispiel #35
0
        public DBDocument CreateDocument(string _url, byte[] _body, string _header)
        {
            DBDocument doc = new DBDocument();
            doc.ID = Guid.NewGuid();
            doc.URL = _url;
            doc.DocType = 0;

            DBDocumentVersion v = new DBDocumentVersion();
            v.ID = Guid.NewGuid();
            v.DocID = doc.ID;
            v.Date = DateTime.Now;
            v.LastUpdate = DateTime.Now;
            v.Version = 0;
            v.Data = _body;
            v.ResponseHeader = _header;

            doc.Versions.Add(v);

            return doc;
        }