public AjaxResult allocateuser( string user, string project, DateTime start, DateTime end, bool ignoreconflicts = false) { // Get allocations for given date string resultValue = "success"; bool confilictingAllocationFound = false; if (!ignoreconflicts) { DBQuery query = new DBQuery("dailyresourcingwidget", "getuserallocation"); query.AddParameter("user", new ObjectId(user)); 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("user", user); newAllocation.AddRelation("project", project); newAllocation["starttimestamp"] = start; newAllocation["endtimestamp"] = end; newAllocation.UpdateDatabase(); } return(new AjaxResult(resultValue)); }
/// <summary> /// Cria um novo jogador com o Nickname e a senha passadas no corpo da chamada /// </summary> /// <param name="player">Dados para criação do novo jogador, incluindo identificação do caller</param> /// <returns>HttpResponseMessage indicando se houve algum problema ou se o jogador foi criado</returns> // POST: api/NewPlayer public HttpResponseMessage Post([FromBody] NewPlayer player) { string DBResponse; if (player == null) { DBResponse = "Formato de dados inválido, faça um Get para receber um exemplo."; return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, DBResponse)); } if ((player.CallerID == null) || (player.CallerPW == null) || (player.Nickname == null) || (player.Password == null)) { DBResponse = "Estão faltando dados, faça um Get para receber um exemplo e envie todas as informações."; return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, DBResponse)); } if ((player.Nickname.Length == 0) || (player.Password.Length == 0)) { DBResponse = "Dados inválidos, Nick e senha não podem estar vazios"; return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, DBResponse)); } if ((player.Nickname.Length > 20) || (player.Password.Length > 20)) { DBResponse = "Sinto muito, para testes, o Nick e a senha estão limitados a 20 caracteres"; return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, DBResponse)); } //Só pra evitar que qualquer um crie novas usuários, fiz um ID/Senha //Inicialmente as variáveis de ambiente estão setadas para JMF e JMF string CallerPW = Environment.GetEnvironmentVariable("CPW"); string CallerID = Environment.GetEnvironmentVariable("CID"); if ((!player.CallerID.Equals(CallerID)) || (!player.CallerPW.Equals(CallerPW))) { //Podia pegar do ambiente também... na próxima vou fazer isso, usar variáveis do ambiente DBResponse = $"Credenciais inválidas, você não pode criar novos usuários"; return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, DBResponse)); } DBResponse = Database.UpdateDB.CreateNewPlayer(player.Nickname, player.Password); if (DBResponse.Equals("OK")) { player.CallerID = ""; player.CallerPW = ""; player.Password = ""; HttpResponseMessage response = Request.CreateResponse <NewPlayer>(HttpStatusCode.Created, player); string uri = Url.Link("DefaultApi", new { id = player.Nickname }); response.Headers.Location = new Uri(uri); return(response); } return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, DBResponse)); }
/// <summary> /// Get data for single user for single day, cache and return it. /// </summary> /// <param name="date"></param> /// <param name="dateKey"></param> /// <param name="userId"></param> /// <returns></returns> private async Task <DataTree> RefreshUserDataForDayAsync(DataTree userTree, DateTime date, string dateKey) { DateTime dayStart = date; var query = new DBQuery("horizontalworkview", "dailyentriesforcache"); query.AddParameter("date", date); query.AddParameter("user", new ObjectId(userTree.Name)); DBResponse cacheQueryResults = await query.FindAsync(); DBCollection dayEntries = cacheQueryResults.FirstCollection; //CacheSingleDayForUser(userTree, dateKey, dayEntries); return((DataTree)dayEntries); }
private ActionResult ExportCsv(string collection, string csvFieldsStr, DBResponse result) { // CSV fields are provided as comma sepearated string. var csvFields = csvFieldsStr.Split(','); string fileName = "listview_" + Guid.NewGuid() + ".csv"; // Use GUID as file name var fullFileName = Path.Combine(HttpContext.Current.Server.MapPath("~"), "public", "csv", fileName); var sw = new StreamWriter(fullFileName); sw.AutoFlush = true; var csv = new CsvWriter(sw); // Instead of returning the list data, convert it to CSV, save into a public location and return a link to the data. if (result.FirstCollection != null) { DataTree documents = (DataTree)result.FirstCollection; var docsArray = ((DataTree)documents).ToArray(); if (docsArray != null && docsArray.Length > 0) { var csvLines = new List <dynamic>(); foreach (var dataTreeDoc in docsArray) { dynamic record = new ExpandoObject(); foreach (var csvField in csvFields) { DataTree schema = Runtime.Schema.First[collection][csvField]; ((IDictionary <String, Object>)record)[GetCsvFieldName(collection, csvField)] = GetCsvValue(schema, dataTreeDoc, csvField); } csvLines.Add(record); } csv.WriteRecords(csvLines); } } var ajaxResult = new DataTree(); ajaxResult["fileName"] = fileName; ajaxResult["success"] = true; return(new AjaxResult(ajaxResult)); }
public DatabaseClient SelectDB2(string targetDB, bool autocreate) { DatabaseClient result = this.Clone(); DBResponse response = result.SelectDB(targetDB, autocreate); if (response == DBResponse.doesNotExist) { return(null); } else if (response == DBResponse.Selected) { return(result); } else { return(null); } }
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)); }
public DBResponse <List <string> > Refresh() { var response = new DBResponse <List <string> > { HasValue = false }; if (Provider.Databases == null) { Provider.Refresh(); } if (Provider.Databases.Contains(Name)) { Tables = Provider.Server.GetDatabase(Name).ToBFS(Provider).Tables; response.HasValue = true; response.Response = Tables; } return(response); }
public DBResponse <bool> Drop() { var response = new DBResponse <bool> { HasValue = false }; if (Provider.Databases == null) { Provider.Refresh(); } if (Provider.Databases.Contains(Name)) { Provider.Server.DropDatabase(Name); response.HasValue = true; response.HasValue = true; } return(response); }
public DBResponse <T> Find(Expression <Func <T, bool> > filter) { var response = new DBResponse <T> { HasValue = false }; try { response.HasValue = true; response.Response = Database.Provider.Server .GetDatabase(Database.Name) .GetCollection <T>(Name) .Find <T>(filter).First(); return(response); } catch (MongoException) { return(response); } }
public ActionResult getprojects( string projectmanager, string searchterms, string orderby, bool ascending, int documentsperpage, int page) { var splitters = new char[] { ' ' }; string[] splitTerms = searchterms.Split(splitters, StringSplitOptions.RemoveEmptyEntries); DBQuery query = QueryGetProjects( splitTerms, orderby, ascending, documentsperpage, page, projectmanager); if (query != null) { DBResponse response = query.Find(); DataTree qi = response.QueryInfo; return(new AjaxResult(GetJsonFromProjectsCollection((DataTree)response.FirstCollection))); int totalRecords = (int)qi["totalrecords"]; // Max page to refer to is number of pages -1 int maxPage = (int)Math.Ceiling((decimal)totalRecords / (decimal)documentsperpage) - 1; totalRecords = (int)qi["totalrecords"]; return(new AjaxResult(GetJsonFromProjectsCollection((DataTree)query.Find().FirstCollection))); } else { return(new AjaxResult("")); } }
public ActionResult InsertLoanInfo(LoanBase_t loan) { var response = new DBResponse(); try { var job = _dalLoan.InsertLoanBase_t(loan); if (job.Any()) { if (job.FirstOrDefault().Id > 0) { response.Id = job.FirstOrDefault().Id; response.StatusCode = "200"; response.StatusMessage = "Success"; } else { response.Id = -1; response.StatusCode = "501"; response.StatusMessage = job.FirstOrDefault().StatusMessage; } } else { response.StatusCode = "404"; response.StatusMessage = "No available job"; } } catch (Exception ex) { response.Id = -1; response.StatusCode = "500"; response.StatusMessage = ex.Message.ToString(); } var camelCaseFormatter = new JsonSerializerSettings(); camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver(); return(Json(JsonConvert.SerializeObject(response, camelCaseFormatter), JsonRequestBehavior.AllowGet)); }
public DBResponse <bool> Delete(Expression <Func <T, bool> > filter) { var response = new DBResponse <bool> { HasValue = false }; try { Database.Provider.Server .GetDatabase(Database.Name) .GetCollection <T>(Name) .DeleteOne(filter); response.HasValue = true; response.Response = true; return(response); } catch (MongoException) { return(response); } }
public DBResponse <bool> Drop() { var response = new DBResponse <bool> { HasValue = false }; try { Database.Provider.Server .GetDatabase(Database.Name) .DropCollection(Name); response.HasValue = true; response.Response = true; Database.Refresh(); return(response); } catch (MongoException) { return(response); } }
public async Task <IActionResult> ForgotPassword([FromBody] string Username) { DBResponse objResponse = new DBResponse(); try { if (!string.IsNullOrEmpty(Username)) { UserDetails acc = new UserDetails(); UserInfo obj = acc.GetUserInfo(new UserInfo { Username = Username }); string recoveryToken = acc.GenerateToken(Username); if (obj != null && obj.UserID > 0 && !string.IsNullOrEmpty(recoveryToken)) { EmailService objEmailService = new EmailService(); string url = ConfigurationSetting.WebAppUrl; objEmailService.ForgetPassword(TemplateCode.FORGETPASSWORD.ToString(), obj.Email, obj.FirstName, url, recoveryToken); objResponse.Message = "Thank You! Account recovery email sent to " + obj.Email; objResponse.Result = true; } else { objResponse.Message = "Email is not related to any existing account!"; } } else { objResponse.Message = AppMessage.UnknownError; } } catch (Exception ex) { objResponse.Message = ex.Message; CLogger.WriteLog(ProjectSource.WebApi, ELogLevel.ERROR, "ERROR ocurred in Account Controller while calling ForgotPassword Action, Ex.: " + ex.Message); } return(Ok(new { Response = objResponse })); }
public DBResponse AddMessageToInbox(MessageUM newmessage) { var response = new DBResponse(); var fromuser = _applicationUserRep.GetUserByUserName(newmessage.FromId); var touser = _applicationUserRep.GetUserByUserName(newmessage.ToId); var receiptor = new List <MessageReceipter>() { new MessageReceipter() { ReceipterUser = touser, } }; var message = new UserMessage() { SendDate = newmessage.SendDate, ReadDate = newmessage.ReadDate, Receivedate = newmessage.ReceiveDate, MessageReceipters = receiptor }; if (fromuser == null || touser == null) { response.IsSucced = false; response.Messages.Add("user not exist!"); return(response); } message.FromUser = fromuser; _context.UserMessages.Add(message); var resp = _context.SaveChanges(); // response.IsSucced = false; // response.Messages.Add("Data cannot insert to database!"); return(response); }
public static DBResponse <MongoTable <T> > GetTable <T>(this MongoDatabase db, string Name) { var response = new DBResponse <MongoTable <T> > { HasValue = false }; if (db.Provider == null) { return(response); } else { if (db.Tables == null) { db.Refresh(); } response.HasValue = true; response.Response = db.Provider.Server.GetDatabase(db.Name).GetCollection <T>(Name).ToBFS(db); db.Refresh(); return(response); } }
private async Task CacheAllDaysInRangeForUserAsync(DataTree userTree, DateTime start, DateTime end) { logger.LogTrace("Caching days for user in a single query", userTree.Name, start, end); var query = new DBQuery("horizontalworkview", "dailyentriesforcache_range"); query.AddParameter("start", start); query.AddParameter("end", end); query.AddParameter("user", new ObjectId(userTree.Name)); DBResponse queryResult = await query.FindAsync(); InvalidateDayRange(userTree, start, end); // Cache each entry foreach (DataTree entryType in queryResult.FirstCollection) { foreach (DataTree entry in entryType) { documents[entry["_id"]] = entry; } } }
public async Task <IActionResult> CheckTokenResetPassword(string recoveryToken) { DBResponse objResponse = new DBResponse(); try { if (!string.IsNullOrEmpty(recoveryToken)) { UserDetails objUserDetails = new UserDetails(); TokenBucket objTokenBucket = new TokenBucket(); objTokenBucket = objUserDetails.GetToken(recoveryToken); if (objTokenBucket != null && objTokenBucket.ID > 0) { if (objTokenBucket.ValidFrom <= DateTime.Now && objTokenBucket.ValidTo >= DateTime.Now && (!objTokenBucket.IsUsed) && (objTokenBucket.IsActive)) { objResponse.Result = true; objResponse.Message = ""; } else { objResponse.Message = "Token request is expired!."; } } else { objResponse.Message = "invalid Token request!."; } } } catch (Exception ex) { CLogger.WriteLog(ProjectSource.WebApi, ELogLevel.ERROR, "ERROR ocurred in Account Controller while calling CheckTokenResetPassword Action, Ex.: " + ex.Message); } return(Ok(new { Response = objResponse })); }
public DBResponse <BaseServerProvider <MongoClient> > TryConnect() { Log(Name, "Connecting..."); var response = new DBResponse <BaseServerProvider <MongoClient> >() { HasValue = false }; try { var _server = new MongoClient(new MongoClientSettings { Server = new MongoServerAddress(ConnectionString), ClusterConfigurator = config => config.ConfigureCluster( settings => settings.With(serverSelectionTimeout: TimeSpan.FromSeconds(1)) ) }); _server.StartSession(); Provider.Server = _server; Provider.Status = ServerStatus.CONNECTED; Provider.Databases = _server.ListDatabaseNames().ToList(); response.Response = Provider; } catch (TimeoutException) { Provider.Status = ServerStatus.DISCONNECTED; Warn(Name, "Conection Unreachable."); } catch (ArgumentException) { Provider.Status = ServerStatus.INVALID; Warn(Name, "Invalid Connection String. Connection Canceled."); } return(response); }
public ActionResult getsubprojects( string parentproject) { int MaxSubProjects = (int)Runtime.Config["tro"]["dataview"]["maxsubprojects"].GetValueOrDefault(300); DBQuery query = QueryGetProjects( null, "name", false, MaxSubProjects, 0, string.Empty); if (query != null) { DBResponse response = query.Find(); DataTree qi = response.QueryInfo; return(new AjaxResult(GetJsonFromProjectsCollection((DataTree)response.FirstCollection))); } else { return(new AjaxResult("")); } }
public ActionResult InsertReceiptVoucher(VoucherInsertRequest request) { var ledgerRequest = new LedgerInsertRequest(); var response = new DBResponse(); try { ledgerRequest.ledgerList = request.ledgerList; var job = _dalLedger.InsertVoucher(request); if (job.FirstOrDefault().Id > 0) { _dalLedger.InsertLedger(ledgerRequest); response.Id = job.FirstOrDefault().Id; response.StatusCode = "200"; response.StatusMessage = job.FirstOrDefault().StatusMessage; } else { response.Id = job.FirstOrDefault().Id; response.StatusCode = "409"; response.StatusMessage = job.FirstOrDefault().StatusMessage; } } catch (Exception ex) { response.Id = -1; response.StatusCode = "500"; response.StatusMessage = ex.Message.ToString(); } var camelCaseFormatter = new JsonSerializerSettings(); camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver(); return(Json(JsonConvert.SerializeObject(response, camelCaseFormatter), JsonRequestBehavior.AllowGet)); }
public ActionResult pasteday(string sourceday, string targetday) { if ((bool)Runtime.Features["timetracking"]) { return(new AjaxResult("Copying not supported for timetracking.")); } logger.LogInfo("copying entries from one date to another", sourceday, targetday); DateTime sourceDay = DateTime.ParseExact(sourceday, "yyyyMMdd", CultureInfo.InvariantCulture); sourceDay = new DateTime(sourceDay.Year, sourceDay.Month, sourceDay.Day, sourceDay.Hour, sourceDay.Minute, sourceDay.Second, DateTimeKind.Utc); DateTime targetDay = DateTime.ParseExact(targetday, "yyyyMMdd", CultureInfo.InvariantCulture); targetDay = new DateTime(targetDay.Year, targetDay.Month, targetDay.Day, targetDay.Hour, targetDay.Minute, targetDay.Second, DateTimeKind.Utc); var query = new DBQuery("workentries", "workforday"); query.AddParameter("start", sourceDay); query.AddParameter("end", sourceDay); query.AddParameter("user", new ObjectId(Runtime.SessionManager.CurrentUser[DBQuery.Id])); DBResponse response = query.Find(); DBCollection timesheetEntries = response["timesheetentry"]; DBCollection abseneceEntries = response["absenceentry"]; DBCollection dayEntries = response["dayentry"]; var tasks = new List <Task <bool> >(); bool isTargetInThePast = (DateTime.Compare(DateTime.UtcNow, targetDay) > 0); // Only ever copy absences for future if (isTargetInThePast) { tasks.Add(CopyEntriesToDay(timesheetEntries, targetDay)); tasks.Add(CopyEntriesToDay(dayEntries, targetDay)); tasks.Add(CopyEntriesToDay(abseneceEntries, targetDay)); } else { logger.LogDebug("Copy target date is in the future"); if ((bool)Runtime.Features["allowfutureabsences"]) { tasks.Add(CopyEntriesToDay(abseneceEntries, targetDay)); } } Task.WaitAll(tasks.ToArray()); bool somethingFiltered = false; foreach (var task in tasks) { if (task.Result) { somethingFiltered = true; } } return(new AjaxResult(somethingFiltered ? "filtered" : "success")); }
public ActionResult getresultsrelation( string terms, string rootschema, string collection, string valuename, string relationtarget, string itemid = "", string filtercontroller = "", string filteraction = "") { var splitters = new char[] { ' ' }; string[] splitTerms = terms.Split(splitters, StringSplitOptions.RemoveEmptyEntries); if (removeWildcards) { RemoveWildcards(splitTerms); } // In case there are no search terms, use the default value. if (splitTerms.Length == 0) { DataTree results = GetDefaultResults( rootschema, collection, valuename, relationtarget, itemid, filtercontroller, filteraction); if (results == null) { return(NamedView("searchfilter", "searchfilterresult", MC2EmptyValue.EmptyValue)); } else { return(NamedView("searchfilter", "searchfilterresult", results)); } } List <IMongoQuery> filterQueries = new List <IMongoQuery>(); IMongoQuery query = Runtime.Filters.GetFilterQuery(filtercontroller, filteraction); if (query != null) { filterQueries.Add(query); } string relationTarget = Runtime.Schema.GetRelationTarget(rootschema, collection, valuename); DataTree schema = Runtime.RunBlock("core", "schemafor", relationTarget); DBQuery resultsQuery = QuerySearchFilterTerm(splitTerms, schema, relationTarget, -1, filterQueries.ToArray()); DBResponse response = null; if (resultsQuery != null) { response = resultsQuery.Find(); List <string> nameFields = Schema.GetNameFields(schema); FilterResults((DataTree)response.FirstCollection, Schema.GetSearchFields(schema), nameFields); } if (response != null && response.FirstCollection.Count > 0) { return(NamedView("searchfilter", "searchfilterresult", (MC2Value)response.FirstCollection, response.QueryInfo)); } else { return(NamedView("searchfilter", "searchfilterresult", MC2EmptyValue.EmptyValue)); } }
public AjaxResult gettotals( string userfilter, string projectfilter, string assetfilter, string profitcenterfilter, string resourceprofitcenterfilter, string resourcebusinessarea, string resourcefunctionalarea, string managerprojectsfilter, string payrollperiodfilter, string favouriteusersfilter, bool showonlyentriesnotaccepted, MC2DateTimeValue daterangestart = null, MC2DateTimeValue daterangeend = null) { int maxTotalDocuments = (int)Runtime.Config["totalwork"]["maxdocuments"].GetValueOrDefault(1000); var timesheetQueries = new List <IMongoQuery>(); var absenceQueries = new List <IMongoQuery>(); var expenseQueries = new List <IMongoQuery>(); SystemsGarden.mc2.tro.approveworklistview.AddFiltersToQuery( "timesheetentry", userfilter, projectfilter, assetfilter, profitcenterfilter, resourceprofitcenterfilter, resourcebusinessarea, resourcefunctionalarea, managerprojectsfilter, payrollperiodfilter, favouriteusersfilter, daterangestart, daterangeend, showonlyentriesnotaccepted, timesheetQueries); SystemsGarden.mc2.tro.approveworklistview.AddFiltersToQuery( "absenceentry", userfilter, projectfilter, assetfilter, profitcenterfilter, resourceprofitcenterfilter, resourcebusinessarea, resourcefunctionalarea, managerprojectsfilter, payrollperiodfilter, favouriteusersfilter, daterangestart, daterangeend, showonlyentriesnotaccepted, absenceQueries); SystemsGarden.mc2.tro.approveworklistview.AddFiltersToQuery( "dayentry", userfilter, projectfilter, assetfilter, profitcenterfilter, resourceprofitcenterfilter, resourcebusinessarea, resourcefunctionalarea, managerprojectsfilter, payrollperiodfilter, favouriteusersfilter, daterangestart, daterangeend, showonlyentriesnotaccepted, expenseQueries); DBQuery totalsQuery = new DBQuery(); totalsQuery["timesheetentry"][DBQuery.Condition] = Query.And(timesheetQueries).ToString(); totalsQuery["timesheetentry"][DBQuery.DocumentsPerPage] = maxTotalDocuments; totalsQuery["timesheetentry"][DBQuery.SpecifiedFieldsOnly] = true; totalsQuery["timesheetentry"]["duration"].Create(); totalsQuery["timesheetentry"]["timesheetentrydetailpaytype"].Create(); totalsQuery["timesheetentry"]["user"].Create(); totalsQuery["timesheetentry"]["project"].Create(); totalsQuery["absenceentry"][DBQuery.Condition] = Query.And(absenceQueries).ToString(); totalsQuery["absenceentry"][DBQuery.DocumentsPerPage] = maxTotalDocuments; totalsQuery["absenceentry"][DBQuery.SpecifiedFieldsOnly] = true; totalsQuery["absenceentry"]["duration"].Create(); totalsQuery["absenceentry"]["absenceentrytype"].Create(); totalsQuery["absenceentry"]["user"].Create(); totalsQuery["dayentry"][DBQuery.Condition] = Query.And(expenseQueries).ToString(); totalsQuery["dayentry"][DBQuery.DocumentsPerPage] = maxTotalDocuments; totalsQuery["dayentry"][DBQuery.SpecifiedFieldsOnly] = true; totalsQuery["dayentry"]["amount"].Create(); totalsQuery["dayentry"]["dayentrytype"].Create(); totalsQuery["dayentry"]["user"].Create(); DBResponse totalsResult = totalsQuery.Find(); if (totalsResult["timesheetentry"].Count >= maxTotalDocuments || totalsResult["dayentry"].Count >= maxTotalDocuments || totalsResult["absenceentry"].Count >= maxTotalDocuments) { return(new AjaxResult("too many results")); } DataTree userTotals = CountResults(totalsResult); return(new AjaxResult((DataTree)userTotals)); }
public ActionResult relationdropdown( string collection, string filtercontroller = "", string filteraction = "") { DataTree schema = Runtime.Schema.First[collection]; string filter = schema["collection"]["listfilter"]; string orderBy = schema["collection"]["orderby"]; bool ascending = (bool)schema["collection"]["ascending"].GetValueOrDefault(false); // Combine given filter and filter from schema. if (!string.IsNullOrEmpty(filtercontroller) && !string.IsNullOrEmpty(filteraction)) { IMongoQuery customFilter = this.Runtime.Filters.GetFilterQuery(filtercontroller, filteraction); if (string.IsNullOrEmpty(filter)) { } else { BsonDocument doc = MongoDB.Bson.Serialization .BsonSerializer.Deserialize <BsonDocument>(filter); var combinedFilter = Query.And(new QueryDocument(doc), customFilter); filter = combinedFilter.ToString(); } } var query = new DBQuery(); if (!string.IsNullOrEmpty(orderBy)) { query[collection][DBQuery.OrderBy] = orderBy; query[collection][DBQuery.Ascending] = ascending; } if (string.IsNullOrEmpty(filter)) { query[collection][DBQuery.Condition] = DBQuery.All; } else { query[collection][DBQuery.Condition] = filter; } query[collection][DBQuery.DocumentsPerPage] = DropdownMaxDocuments; DBResponse response = query.Find(); DataTree filteredResults = new DataTree("results"); foreach (DataTree result in response.FirstCollection) { DataTree filteredResult = filteredResults.Add(result.Name); List <string> nameFields = Schema.GetNameFields(Runtime.Schema.First[collection]); string displayName = ""; bool first = false; foreach (string nameField in nameFields) { if (first) { first = false; } else if (!displayName.EndsWith(" ") && !string.IsNullOrEmpty(displayName)) { displayName += " "; } displayName += result[nameField]; } filteredResult["name"] = displayName; } return(new AjaxResult(filteredResults)); }
private DataTree CountResults(DBResponse totalsResult) { var userTotals = new DataTree(); userTotals.JsonSerializationType = JsonSerializationType.ChildrenAsArrays; bool useSocialProject = (bool)Runtime.Config["application"]["features"]["enablesocialproject"]; string socialProjectId = null; if (useSocialProject) { socialProjectId = GetSocialProjectId(); } DBCollection timesheetEntries = totalsResult["timesheetentry"]; foreach (DBDocument timesheetEntry in timesheetEntries) { string userId = VerifyUser(timesheetEntry, userTotals); if (string.IsNullOrEmpty(userId)) { continue; } string timsheetEntryId = timesheetEntry[DBQuery.Id]; DBDocument payType = GetPayType(timesheetEntry["timesheetentrydetailpaytype"][DBQuery.Id]); if (payType == null) { continue; } string payTypeId = payType[DBQuery.Id]; if ((bool)payType["countsasregularhours"]) { userTotals[userId]["totalworkinghours"] = (decimal)userTotals[userId]["totalworkinghours"].GetValueOrDefault(0) + DurationToHours((int)timesheetEntry["duration"].GetValueOrDefault(0)); } if ((bool)payType["isovertime50"] || (bool)payType["isovertime100"] || (bool)payType["isovertime150"] || (bool)payType["isovertime200"]) { userTotals[userId]["overtime"] = (decimal)userTotals[userId]["ovetime"].GetValueOrDefault(0) + DurationToHours((int)timesheetEntry["duration"].GetValueOrDefault(0)); } if (useSocialProject && socialProjectId != null && timesheetEntry["project"][DBQuery.Id] == socialProjectId) { userTotals[userId]["socialproject"] = (decimal)userTotals[userId]["ovetime"].GetValueOrDefault(0) + DurationToHours((int)timesheetEntry["duration"].GetValueOrDefault(0)); } } DBCollection absenceEntries = totalsResult["absenceentry"]; foreach (DBDocument absenceEntry in absenceEntries) { string userId = VerifyUser(absenceEntry, userTotals); if (string.IsNullOrEmpty(userId)) { continue; } string absenceId = absenceEntry[DBQuery.Id]; userTotals[userId]["totalabsences"] = (decimal)userTotals[userId]["totalabsences"].GetValueOrDefault(0) + DurationToHours((int)absenceEntry["duration"].GetValueOrDefault(0)); } DBCollection expenseEntries = totalsResult["dayentry"]; foreach (DBDocument expenseEntry in expenseEntries) { string userId = VerifyUser(expenseEntry, userTotals); if (string.IsNullOrEmpty(userId)) { continue; } string expenseTypeId = expenseEntry["dayentrytype"][DBQuery.Id]; DBDocument expenseType = GetExpenseType(expenseTypeId); if (expenseType == null) { continue; } if ((bool)expenseType["totalsgroup"]) { userTotals[userId]["expensetypes"][expenseType["totalsgroup"]] = (int)userTotals[userId]["expensetypes"][expenseType["totalsgroup"]].GetValueOrDefault(0) + (int)expenseEntry["amount"].GetValueOrDefault(0); } } return(userTotals); }
/// <summary> /// Atualiza dados do Jogador /// </summary> /// <param name="id">Código para atualização</param> /// <param name="player">Dados de atualização</param> /// <returns> Mensagem com OK ou descrição do erro </returns> // PUT: api/UpdScores/5 public HttpResponseMessage Put(int id, [FromBody] PlayerStatus player) { string DBResponse; if (id != 42) //Just an easy check, if you don't know why 42, I do not want to work with you :-) { DBResponse = "PUT inválido."; return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, DBResponse)); } if (player == null) { DBResponse = "Formato de dados inválido, faça um Get para receber um exemplo."; return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, DBResponse)); } if ((player.CallerID == null) || (player.CallerPW == null) || (player.Nickname == null) || (player.Password == null) || (player.NewStats == null)) { DBResponse = "Estão faltando dados, faça um Get para receber um exemplo e envie todas as informações."; return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, DBResponse)); } if (player.NewStats.Count == 0) { DBResponse = "Você deve enviar pelo menos um valor no NewStat"; return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, DBResponse)); } if ((player.Nickname.Length == 0) || (player.Password.Length == 0)) { DBResponse = "Dados inválidos, Nick e senha não podem estar vazios"; return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, DBResponse)); } int NScores = Math.Min(6, player.NewStats.Count); int[] NewScores = new int[NScores]; int total = player.NewStats[0]; int parcial = 0; for (int i = 0; i < NewScores.Length; i++) { if (player.NewStats[i] < 0) { DBResponse = "Não são permitidos dados negativos."; return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, DBResponse)); } NewScores[i] = player.NewStats[i]; if (i % 3 != 0) { parcial += player.NewStats[i]; } if (i == 3) { if (parcial > total) { DBResponse = "Dados parciais maiores que o total."; return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, DBResponse)); } if (player.NewStats.Count > 3) { total = player.NewStats[3]; parcial = 0; } } if ((i > 2) && (player.NewStats[i] > player.NewStats[i - 3])) { DBResponse = "Dados semanais maiores que os totais."; return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, DBResponse)); } } if (parcial > total) { DBResponse = "Dados parciais maiores que o total."; return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, DBResponse)); } //Só pra evitar que qualquer um atualize os dados, fiz um ID/Senha //Inicialmente as variáveis de ambiente estão setadas para JMF e JMF //Podia ter usado credenciais deferentes para create e update... string CallerPW = Environment.GetEnvironmentVariable("CPW"); string CallerID = Environment.GetEnvironmentVariable("CID"); if ((!player.CallerID.Equals(CallerID)) || (!player.CallerPW.Equals(CallerPW))) { DBResponse = "Credenciais inválidas, você não pode atualizar o status"; return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, DBResponse)); } DBResponse = Database.UpdateDB.UpdatePlayerStats(player.Nickname, player.Password, NewScores); if (DBResponse.Equals("OK")) { player.CallerID = ""; player.CallerPW = ""; player.Password = ""; player.NewStats.Clear(); for (int i = 0; i < NewScores.Length; i++) { player.NewStats.Add(NewScores[i]); } HttpResponseMessage response = Request.CreateResponse <PlayerStatus>(HttpStatusCode.Created, player); string uri = Url.Link("DefaultApi", new { id = player.Nickname }); response.Headers.Location = new Uri(uri); return(response); } return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, DBResponse)); }
public ActionResult InsertCompanyInfo() { var response = new DBResponse(); var companyInfo = new CompanyInfo(); try { string filename = ""; companyInfo.Id = Convert.ToInt32(Request["Id"]); companyInfo.Name = Convert.ToString(Request["Name"]); companyInfo.Contact = Convert.ToString(Request["Contact"]); companyInfo.Email = Convert.ToString(Request["Email"]); companyInfo.Address = Convert.ToString(Request["Address"]); if (Request.Files.Count == 0) { response.Id = -1; response.StatusCode = "501"; response.StatusMessage = "Please Uplaod a file"; } else { for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; filename = companyInfo.Id + "_" + Path.GetFileName(Request.Files[i].FileName); var TemporaryPath = Server.MapPath(uploadPath) + filename; file.SaveAs(TemporaryPath); } companyInfo.LogoLocation = filename; var job = _dalCompany.InsertCompany(companyInfo); if (job.Any()) { if (job.FirstOrDefault().Id > 0) { response.Id = job.FirstOrDefault().Id; response.StatusCode = "200"; response.StatusMessage = "Success"; } else { response.Id = -1; response.StatusCode = "501"; response.StatusMessage = job.FirstOrDefault().StatusMessage; } } else { response.StatusCode = "404"; response.StatusMessage = "No available job"; } } } catch (Exception ex) { response.Id = -1; response.StatusCode = "500"; response.StatusMessage = ex.Message.ToString(); } var camelCaseFormatter = new JsonSerializerSettings(); camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver(); return(Json(JsonConvert.SerializeObject(response, camelCaseFormatter), JsonRequestBehavior.AllowGet)); }
public ActionResult showfilteredlistview( string terms, string collection, string orderby, bool ascending, int documentsperpage, int page, string relation, string relationid, bool islocalrelation, string localcollection, IMongoQuery filter, bool itemselection = false, string viewcontroller = "listview", string viewaction = "listviewresults", bool includeTotals = false, bool saveAsCsv = false, string csvFieldsStr = "") { var splitters = new char[] { ' ' }; string[] splitTerms = terms.Split(splitters, StringSplitOptions.RemoveEmptyEntries); var dbQueries = new List <IMongoQuery>(); DataTree schema = Runtime.Schema.First[collection]; if (string.IsNullOrEmpty(orderby) || orderby == "__default") { orderby = (string)schema["collection"]["orderby"].GetValueOrDefault(""); // If we have custom order from schema, get custom ascending value as well. if (!string.IsNullOrEmpty(orderby)) { ascending = (bool)schema["collection"]["ascending"].GetValueOrDefault(false); } else { orderby = globalDefaultOrder; } } if (filter == null) { filter = GetDefaultFilter(Runtime, collection); } DBQuery listViewQuery; if (islocalrelation) { DataTree localRelations = GetLocalRelationItems(localcollection, relation, relationid); listViewQuery = QueryListViewLocalRelation( splitTerms, schema, collection, orderby, ascending, documentsperpage, page, relation, relationid, localcollection, localRelations, filter); } else { listViewQuery = QueryListView(splitTerms, schema, collection, orderby, ascending, documentsperpage, page, relation, relationid, filter); } if (listViewQuery != null) { listViewQuery[collection][DBQuery.DownloadThumbnails] = true; if (includeTotals) { listViewQuery[collection]["__includetotals"] = true; } // It's possible to extend the default query with the specified custom query. if (schema["collection"].Contains("query")) { DataTree additionalQuery = Runtime.Queries[Runtime.Schema.First.Name][schema["collection"]["query"]]; if (!additionalQuery.Exists) { throw new RuntimeException("Additional query specified for collection doesn't exist: " + schema["collection"]["query"]); } listViewQuery.Merge(additionalQuery); } DBResponse result = listViewQuery.FindAsync().Result; int maxPage = -1; int totalRecords = -1; DataTree qi = result.QueryInfo; bool hasMoreResults = (bool)qi[collection][DBQuery.HasMoreResults]; if (includeTotals) { totalRecords = (int)qi[collection]["totalrecords"]; // Max page to refer to is number of pages -1 maxPage = (int)Math.Ceiling((decimal)totalRecords / (decimal)documentsperpage) - 1; } if (saveAsCsv && csvFieldsStr != "") { return(ExportExcel(collection, csvFieldsStr, result)); } // schema parent is used to pass the original view's controller's name to listview. return(NamedView( viewcontroller, viewaction, (MC2Value)result.FirstCollection, schema.Parent.Name, totalRecords, page, maxPage, itemselection, relation, relationid, hasMoreResults)); } else { return(NamedView( "listview", "listviewresults", MC2EmptyValue.EmptyValue, schema.Parent.Name, 0, 0, itemselection, relationid, false)); } }