public void addContributionTest() { db.addUser(testUser); int numUsers = db.retrieveAllUsers().Count; db.addPortfolio(testPortfolio, numUsers); int numPortfolios = db.retrieveAllPortfolios().Count; db.addProjectToPortfolio(testProject, numPortfolios); int numProjects = db.retrieveAllProjects().Count; Contribution testC = new Contribution() { Title = "TestTitle", Description = "TestDescription", UserId = numUsers, ProjectId = numProjects }; int initialNumContributions = db.retrieveAllContributions().Count; db.addContribution(testC, numProjects); int finalNumContributions = db.retrieveAllContributions().Count; Assert.AreEqual(initialNumContributions + 1, finalNumContributions, "Contribution Add Failed"); User toDelete = db.retrieveUser(numUsers); db.deleteUser(toDelete); int postDeleteUsers = db.retrieveAllUsers().Count; Assert.AreEqual(numUsers - 1, postDeleteUsers, "User Delete Failed"); }
public ActionResult AddContribution(int accountID,int kudos, string item, string currency, double gross, double grossEur, double netEur, string email, string comment, bool isSpring, DateTime date) { using (var db = new ZkDataContext()) { var acc = db.Accounts.Find(accountID); var contrib = new Contribution() { AccountID = accountID, ManuallyAddedAccountID = Global.AccountID, KudosValue = kudos, ItemName = item, IsSpringContribution = isSpring, Comment = comment, OriginalCurrency = currency, OriginalAmount = gross, Euros = grossEur, EurosNet = netEur, Time = date, Name = acc.Name, Email = email }; db.Contributions.InsertOnSubmit(contrib); db.SubmitAndMergeChanges(); acc.Kudos = acc.KudosGained - acc.KudosSpent; db.SubmitAndMergeChanges(); } return RedirectToAction("Index"); }
public void Contribution_Has_Setable_Properties() { var user = Mock.Of <ApplicationUser>(); var date = DateTime.Now; var issue = Mock.Of <Issue>(); var contrib = new Contribution() { ContributionID = 1, Amount = 50.00, Author = user, AuthorID = "1", CreatedAt = date, UpdatedAt = date, Issue = issue, IssueID = 1 }; Assert.AreEqual(1, contrib.ContributionID); Assert.AreEqual(50.00, contrib.Amount); Assert.AreEqual(user, contrib.Author); Assert.AreEqual("1", contrib.AuthorID); Assert.AreEqual(date, contrib.CreatedAt); Assert.AreEqual(date, contrib.UpdatedAt); Assert.AreEqual(issue, contrib.Issue); Assert.AreEqual(1, contrib.IssueID); }
private Contribution GetContribution(P3dColorCounter counter) { if (contributions == null) { contributions = new List <Contribution>(); } for (var i = contributions.Count - 1; i >= 0; i--) { var contribution = contributions[i]; if (contribution.Counter == counter) { return(contribution); } } var newContribution = new Contribution(); contributions.Add(newContribution); newContribution.Counter = counter; return(newContribution); }
public async Task <IActionResult> DeleteUpload(Contribution contribution, int fileId) { var topic = await _context.Submissions.FirstOrDefaultAsync(t => t.Id == contribution.SubmissionId); if (topic.SubmissionDeadline_2 >= DateTime.Now) { var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); if (ModelState.IsValid) { var fileSubmitted = await _context.SubmittedFiles.FindAsync(fileId); System.IO.File.Delete(fileSubmitted.URL); var path = Path.Combine(_env.WebRootPath, _Global.PATH_TEMP, Path.GetFileNameWithoutExtension(fileSubmitted.URL) + ".pdf"); System.IO.File.Delete(path); _context.Remove(fileSubmitted); await _context.SaveChangesAsync(); } } else { } return(RedirectToAction(nameof(Details), new { id = contribution.SubmissionId })); }
public ActionResult AddContribution(int accountID, int kudos, string item, string currency, double gross, double grossEur, double netEur, string email, string comment, bool isSpring, DateTime date) { using (var db = new ZkDataContext()) { var acc = db.Accounts.Find(accountID); var contrib = new Contribution() { AccountID = accountID, ManuallyAddedAccountID = Global.AccountID, KudosValue = kudos, ItemName = item, IsSpringContribution = isSpring, Comment = comment, OriginalCurrency = currency, OriginalAmount = gross, Euros = grossEur, EurosNet = netEur, Time = date, Name = acc.Name, Email = email }; db.Contributions.InsertOnSubmit(contrib); db.SubmitAndMergeChanges(); acc.Kudos = acc.KudosGained - acc.KudosSpent; db.SubmitAndMergeChanges(); } return(RedirectToAction("Index")); }
public Contribution Contribute(int packageId, string contributorEmail, string message, float contribuitionValue) { var contributor = contributorHandler.GetOrInsert(new Contributor { Email = contributorEmail }); var contribute = new Contribution { ContributorId = contributor.Id, PackageId = packageId, Message = message, ContributionValue = contribuitionValue }; var savedContribution = contributionWriter.Save(contribute); emailSender.Send(new Email { To = contributorEmail, Message = weddingMailHandler.Generate(), Ccn = weddingMailHandler.GenerateCcn(), From = weddingMailHandler.FromUser(), Subject = weddingMailHandler.GenerateSubject() }); return(savedContribution); }
/// <summary> /// Handles refreshing after adding. /// </summary> void HandleContributionAddMessage(MessagingService obj, Contribution contribution) { State = LayoutState.Loading; Contributions.Add(contribution); Contributions = new ObservableCollection <Contribution>(Contributions.OrderByDescending(x => x.StartDate).ToList()); State = LayoutState.None; }
public DataMessage Enter(Contribution model) { DataHelper helper = new DataHelper(Configuration); SqlParameter[] sqlParameters = { new SqlParameter("@AuditUserID", UserId), new SqlParameter("@InsuranceNumber", model.InsuranceNumber), new SqlParameter("@Payer", model.Payer), new SqlParameter("@PaymentDate", model.PaymentDate), new SqlParameter("@ProductCode", model.ProductCode), new SqlParameter("@ReceiptNo", model.ReceiptNumber), new SqlParameter("@ReactionType", model.ReactionType), new SqlParameter("@ContributionCategory", model.ContributionCategory), new SqlParameter("@ContributionAmount", model.Amount), new SqlParameter("@PaymentType", model.PaymentType) }; DataMessage message; try { var response = helper.Procedure("uspAPIEnterContribution", sqlParameters, 1); message = new EnterContibutionResponse(response.Code, false, response.Data, 0).Message; } catch (Exception e) { message = new EditFamilyResponse(e).Message; } return(message); }
private async Task FillJson(JArray json, Contribution c) { c = await _context.Contributions .Include(c => c.Comments) .Include(c => c.Author) .FirstOrDefaultAsync(c2 => c2.Id == c.Id); foreach (var c2 in c.Comments) { var c3 = await _context.Contributions .Include(c => c.Comments) .Include(c => c.Author) .FirstOrDefaultAsync(c => c.Id == c2.Id); var item = new JObject(); item.Add("Id", c3.Id); item.Add("DateCreated", c3.DateCreated); item.Add("Upvotes", c3.Upvotes); item.Add("Title", c3.getTitle()); item.Add("Content", c3.Content); var author = new JObject(); author.Add("UserId", c3.Author.UserId); author.Add("Email", c3.Author.Email); item.Add("Author", author); var coms = new JArray(); await FillJson(coms, c3); item.Add("Comments", coms); json.Add(item); } }
public async Task <IActionResult> Edit(int id, [Bind("Id,Payment,PaymentDate,UserId,MonthId")] Contribution contribution) { if (id != contribution.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _unitOfWork.Update(contribution); await _unitOfWork.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ContributionExists(contribution.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["MonthId"] = new SelectList(_unitOfWork.Months.GetDbSet(), "Id", "Name", contribution.MonthId); //ViewData["UserId"] = new SelectList(_context.Users, "Id", "Id", contribution.UserId); ViewData["UserId"] = contribution.UserId; return(View(contribution)); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Converts the specified chunk of XML into a list of contributions /// (i.e. ContributionCollection). /// </summary> /// ------------------------------------------------------------------------------------ public override object Deserialize(string xmlBlob) { // TODO: Deal with approved license objects of contributions. var contributionCollection = GetElementFromXml(xmlBlob).Elements("contributor").Select(e => { Role role; _olacSystem.TryGetRoleByCode(e.Element("role").Value, out role); var contrib = new Contribution(e.Element("name").Value, role); // We have this permissive business because we released versions of SayMore (prior to 1.1.120) which used the local // format, rather than a universal one. var when = e.Element("date").Value; try { contrib.Date = DateTimeExtensions.ParseDateTimePermissivelyWithException(when); } catch (Exception exception) { Logger.WriteEvent("Handled exception in ContributionSerializer.Deserialize:\r\n{0}", exception.ToString()); contrib.Date = DateTime.MinValue; // looked like it would take hours to change scores of methods to propogate a progress thing (e.g. ErrorCollector) down this far. Sigh... progress.WriteError("SayMore had trouble understanding the date '{0}', on a contribution by {1}. For now, it was replaced by {2}", d, contrib.ContributorName, contrib.Date.ToString(CultureInfo.CurrentCulture)); } contrib.Comments = e.Element("notes")?.Value; return(contrib); }); return((contributionCollection.Any()) ? new ContributionCollection(contributionCollection) : null); }
private static string makeErrorMessage(Contribution c, Exception e) { Plugin p = c.parent; return(string.Format("Title: {0}\tAuthor: {1}\nID={2}\n\n{3}", p.title, p.author, c.id, e.ToString())); //! return string.Format("タイトル: {0}\t作者: {1}\nID={2}\n\n{3}",p.title,p.author,c.id,e.ToString()); }
public void Contribute(P3dTeamCounter counter, int count) { if (contributions != null) { for (var i = contributions.Count - 1; i >= 0; i--) { var contribution = contributions[i]; if (contribution.Counter == counter) { contribution.Count = count; return; } } } else { contributions = new List <Contribution>(); } var newContribution = new Contribution(); newContribution.Counter = counter; newContribution.Count = count; contributions.Add(newContribution); }
public void ValidateManualEdit(Contribution contribution) { if (contribution.ContributionType == ContributionType.Owner) { throw new ValidationException($"A contribution of type '{ContributionType.Owner}' cannot be edited directly"); } }
public static string Open(long userId, long count, long days) { if (count <= 0) { return("❌ Указана неверная сумма"); } if (days < 1) { return("❌ Указано неверное количество дней."); } var user = Main.Api.Users.GetUserFromId(userId); if (user.MoneyInBank < count) { return("❌ У Вас недостаточно денег в банке."); } using (var db = new Database()) { var contr = new Contribution() { UserId = userId, CountDay = days, Money = count }; db.Contributions.Add(contr); db.SaveChanges(); UsersCommandHelper.GetHelper().Add("", user.Id); return($"✔ Вы открыли вклад на сумму {count} руб., на {days} дн."); } }
public EditSentenceViewModel(Contribution original) { this.Item = original; Title = Resx.AppResources.EditSentence; SaveCommand = new Command(async() => await ExecuteSaveCommand()); CancelCommand = new Command(async() => await ExecuteCancelCommand()); }
private void ProcessInsertDesignIdea(int id) { TableTopDataClassesDataContext db = Configurations.GetTableTopDB(); var designideas = from d in db.Contributions where d.id == id select d; if (designideas.Count() == 1) { Contribution di = designideas.Single <Contribution>(); User u = find_user_of_contribution(di); Activity a = find_activity_of_contribution(di); if (u == null || a == null) { return; } string cid = a.technical_info.Split(new char[] { ';' })[0]; SContext c = server_api.GetContext(cid); if (c == null) { return; } SNote note = server_api.CreateNote(u.name, "DesignIdea", di.note, c.name, di.status.ToString()); if (note == null) { return; } di.technical_info = note.id.ToString(); db.SubmitChanges(); if (RESTService.Last_Exception != null) { this.errors.Add(RESTService.Last_Exception); } } }
protected void OutputSkillsOfContribution(Contribution contribution) { foreach (ContributionSkill contributionSkill in contribution.ContributionSkills) { Console.Write(contributionSkill.Skill.Title + " "); } }
public void deleteContribution(Contribution c, int projectID) { using (var db = new PortfolioUnleashedContext()) { db.Projects.Include("Contributions").Include(p => p.Contributions.Select(co => co.ContributionMedia)).FirstOrDefault(u => u.Id == projectID) .Contributions.Remove(db.Contributions.Where(con => con.ProjectId == projectID && con.UserId == c.UserId).FirstOrDefault()); if (db.ContributionMediums.Any(co => co.UserId == c.UserId && co.ProjectId == projectID)) //Remove all media for contribution { foreach (ContributionMedium cm in db.ContributionMediums.Where(co => co.UserId == c.UserId && co.ProjectId == projectID)) { db.ContributionMediums.Remove(cm); } } db.Contributions.Remove(db.Contributions.Where(cb => cb.UserId == c.UserId && cb.ProjectId == c.ProjectId).FirstOrDefault()); //Remove the contribution db.SaveChanges(); if (db.Projects.Include("Contributions").FirstOrDefault(proj => proj.Id == projectID).Contributions.Count <= 0) //If no contributions remaining { deleteProjectCompletely(db.Projects.Include("Contributions").FirstOrDefault(prod => prod.Id == projectID)); } else if (db.Users.Include("ProjectPermissions").FirstOrDefault(user => user.Id == c.UserId).ProjectPermissions.Any(proj => proj.IsProjectEditor == true)) //Contributing user was a project editor { if (!db.Users.Include("ProjectPermissions").Any(user => (user.ProjectPermissions.Any(proj => (proj.ProjectId == projectID && proj.IsProjectEditor == true))))) //If no remaining contributing users are project editors { int selectedUserToPromote = db.Projects.Include("Contributions").FirstOrDefault(proj => proj.Id == projectID).Contributions.FirstOrDefault(cont => cont.UserId != null).UserId; db.Users.Include("ProjectPermissions").FirstOrDefault(user => user.Id == selectedUserToPromote).ProjectPermissions.FirstOrDefault(perm => perm.ProjectId == projectID).IsProjectEditor = true; } } if (db.ProjectPermissions.Any(perm => perm.UserId == c.UserId && perm.ProjectId == projectID)) { db.Projects.Include("ProjectPermissions").Where(pr => pr.Id == projectID).FirstOrDefault().ProjectPermissions .Remove(db.ProjectPermissions.Include("Project").Include("User").Where(perm => perm.UserId == c.UserId && perm.ProjectId == projectID).FirstOrDefault()); } db.SaveChanges(); } }
protected void Page_Load(object sender, EventArgs e) { if (Session["UserSession"] != null) { s = (SiteUser)Session["UserSession"]; } else { Session.Clear(); Response.Redirect("~/UI/Default.aspx"); } if (Session["fdbkSession"] != null) { c = (Contribution)Session["fdbkSession"]; if (!IsPostBack) { // add details to form lblTitle.Text = c.Title; ddlStatus.Text = c.Status; txtFeedback.Text = c.Feedback; } } else { Response.Redirect("~/UI/ViewSubmissions.aspx"); } }
public void SavePayroll(SalaryRuleHeaderVm salaryRules) { if (salaryRules.RuleId == 0) { SalaryRuleHeader salaryRule = new SalaryRuleHeader() { Category = salaryRules.Category, Code = salaryRules.Code, IsActive = salaryRules.IsActive, IsOnPayslip = salaryRules.IsOnPayslip, Name = salaryRules.Name, SequenceNo = salaryRules.SequenceNo, }; Add(salaryRule); SalaryRuleDetail salaryRuleDetail = new SalaryRuleDetail() { AmountType = salaryRules.salaryRuleDetailVm.AmountType, ConditionBased = salaryRules.salaryRuleDetailVm.ConditionBased, ContributionRegister = salaryRules.salaryRuleDetailVm.ContributionRegister, PythonCode = salaryRules.salaryRuleDetailVm.PythonCode, RuleId = salaryRule.RuleId }; salaryRuleDetailBO.Add(salaryRuleDetail); Contribution Contribution = new Contribution() { Description = salaryRules.contributionVm.Description, IsActive = salaryRules.contributionVm.IsActive, Name = salaryRules.Name }; contributionBO.Add(Contribution); } }
public ActionResult DealContributionManageSave(List <int> GameID, List <decimal> AllContribution, string ContributionID) { int n = 0; decimal[] allContribution = AllContribution.ToArray(); foreach (var item in GameID) { if (allContribution[n] != 0 && allContribution[n] < 200) { Contribution contribution = EFContribution.Contributions.Where(c => c.ContributionID == ContributionID && c.GameID == item).FirstOrDefault(); if (contribution != null) { contribution.AllContribution = allContribution[n]; EFContribution.UpdateContribution(contribution); } } n++; } ContributionList contributionList = EFContribution.ContributionLists.Where(c => c.ContributionID == ContributionID).FirstOrDefault(); contributionViewModel = new ContributionViewModel { ContributionLists = EFContribution.ContributionLists.OrderByDescending(c => c.ContributionID).Take(10).ToList(), Contributions = EFContribution.Contributions.Where(c => c.ContributionID == ContributionID).OrderBy(c => c.GameID).ToList(), GameMembers = EFGameMember.gameMembers, ContributionList = contributionList, }; return(PartialView("_TabContent", contributionViewModel)); }
public ActionResult Contributions(int simchaId) { IEnumerable <Contributor> contributors = dB.GetContributorsWithBalances(); IEnumerable <Contribution> contributions = dB.GetContributionsForSimcha(simchaId); List <ContributorContribution> ccs = new List <ContributorContribution>(); foreach (var c in contributors) { Contribution contribution = contributions.FirstOrDefault(item => item.ContributorId == c.Id); var cc = new ContributorContribution { ContributorWithBalance = c }; if (contribution != null) { cc.Contribute = true; cc.Amount = contribution.Amount; } ccs.Add(cc); } return(View(new ContributionsViewModel { Contributors = ccs, Simcha = dB.GetSimchaById(simchaId) })); }
public static bool UpdateContributionStatus(Contribution c, string status, string feedback) { // insert the contribution into database with file SqlConnection myConnection = new SqlConnection(Properties.Settings.Default.PeachTreeConnectionString); string strQuery = "UPDATE PTA_Contribution SET " + "Cont_Status = @paramStatus, " + "feedback = @paramfeedback " + "WHERE PTA_ID_Contribution = @paramContID; "; SqlCommand cmd = new SqlCommand(strQuery, myConnection); cmd.Parameters.AddWithValue("@paramStatus", status); cmd.Parameters.AddWithValue("@paramfeedback", feedback); cmd.Parameters.AddWithValue("@paramContID", c.ContributionID); try { myConnection.Open(); cmd.ExecuteNonQuery(); return(true); } catch (Exception e) { Console.WriteLine(e.ToString()); return(false); } finally { myConnection.Close(); } }
public async Task <IActionResult> Edit(int id, [Bind("Id,Status,ContributorId,TopicId")] Contribution contribution) { if (id != contribution.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(contribution); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ContributionExists(contribution.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["ContributorId"] = new SelectList(_context.Users, "Id", "Id", contribution.ContributorId); ViewData["TopicId"] = new SelectList(_context.Topic, "Id", "Id", contribution.TopicId); return(View(contribution)); }
/// <summary> /// Duplicate with git probvider /// </summary> Dictionary <string, Contribution> CalculateContributionsParallel(IProgress progress, List <string> localFiles) { // Calculate main developer for each file var fileToContribution = new ConcurrentDictionary <string, Contribution>(); var all = localFiles.Count; Parallel.ForEach(localFiles, new ParallelOptions { MaxDegreeOfParallelism = 4 }, file => { var work = CalculateDeveloperWork(file); var contribution = new Contribution(work); var result = fileToContribution.TryAdd(file, contribution); Debug.Assert(result); // Progress var count = fileToContribution.Count; progress.Message($"Calculating work {count}/{all}"); }); return(fileToContribution.ToDictionary(pair => pair.Key.ToLowerInvariant(), pair => pair.Value)); }
public void Clone_RolesAreDifferentObject() { var r = new Role("dev", "developer", "def"); var c = new Contribution("name", r).Clone() as Contribution; Assert.AreNotSame(r, c.Role); }
public void AreContentsEqual_NamesDifferent_ReturnsFalse() { var c1 = new Contribution("joey", null); var c2 = new Contribution("bucky", null); Assert.IsFalse(c1.AreContentsEqual(c2)); }
public Contribution Add(Contribution contribution) { contribution.Time = DateTime.Now; appDbContext.Contributions.Add(contribution); appDbContext.SaveChanges(); return(contribution); }
public async Task <IActionResult> PutContribution([FromRoute] int id, [FromBody] Contribution contribution) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != contribution.Id) { return(BadRequest()); } _unitOfWork.Entry(contribution).State = EntityState.Modified; try { await _unitOfWork.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ContributionExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public void addContribution(Contribution c, int projectID) { using (var db = new PortfolioUnleashedContext()) { db.Projects.Include("Contributions").Include(p => p.Contributions.Select(co => co.ContributionMedia)).FirstOrDefault(u => u.Id == projectID).Contributions.Add(c); db.SaveChanges(); } }
public ActionResult Create(Contribution contribution) { if (ModelState.IsValid) { db.Contribute.Add(contribution); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.TypeID = new SelectList(db.ContributionTypes, "ID", "type", contribution.TypeID); ViewBag.E_ID = new SelectList(db.Events, "E_ID", "Name", contribution.E_ID); return View(contribution); }
public static List<Contribution> contributionListFromVMContributionList(List<VMContribution> vmContributions) { List<Contribution> contributions = new List<Contribution>(); foreach (VMContribution vmContribution in vmContributions) { Contribution contribution = new Contribution() { UserId = vmContribution.UserId, ProjectId = vmContribution.ProjectId, Title = vmContribution.Title, Description = vmContribution.Description, ContributionMedia = contributionMediumListFromVMContributionMediumList(vmContribution.Media) }; contributions.Add(contribution); } return contributions; }
public void AddContribution(Contribution contribution) { // TODO: Tables already have indices. Ask Richard how to make this more efficient so don't need "FirstOrDefault" // Retrieve existing foreign keys if they exist var author = _db.Authors.FirstOrDefault(a => a.Name.Equals(contribution.Author.Name)); if (author != null) contribution.Author = author; var spec = _db.Specs.FirstOrDefault(a => a.Name.Equals(contribution.Spec.Name)); if (spec != null) contribution.Spec = spec; var tracker = _db.Trackers.FirstOrDefault(a => a.Name.Equals(contribution.Tracker.Name)); if (tracker != null) contribution.Tracker = tracker; var organization = _db.Organizations.FirstOrDefault(a => a.Name.Equals(contribution.Organization.Name)); if (organization != null) contribution.Organization = organization; _db.ContributionsInternal.Add(contribution); _db.SaveChanges(); }
// add an initial comment (that's not actually a comment; it is used to show a contribution's user provided attributes) public void initialize_comments(Contribution the_contribution) { //string comment = ""; //if (the_contribution.note != null && the_contribution.note != "") // comment = the_contribution.note + "\r\n"; //comment += configurations.contribution_comment_date; //comment += the_contribution.date.ToString(); //comment += "\r\n"; //if (the_contribution.tags != "") // comment = comment + configurations.contribution_comment_tag + the_contribution.tags + "\r\n"; //if (the_contribution.location_id != 0) // comment = comment + configurations.contribution_comment_location + the_contribution.location_id.ToString() + ": " + the_contribution.Location.name; this.expander_metadata_panel.Background = Brushes.LightGray; //Note if (the_contribution.note != null && the_contribution.note != "") metadata1.Text = the_contribution.note; else { if (configurations.show_empty_metadata) metadata1.Text = "[Empty]"; else metadata1.Visibility = System.Windows.Visibility.Collapsed; } //metadata.Inlines.Add(new LineBreak()); //User and date User u = configurations.find_user_of_contribution(the_contribution); string date1 = configurations.GetDate_Formatted(the_contribution.date); string date2 = the_contribution.date.ToString("hh:mm tt"); if (u == null) { //metadata.Inlines.Add("Date: "); metadata2.Inlines.Add(new Bold(new Run(date1 + " " + date2))); } else { metadata2.Inlines.Add(configurations.contribution_comment_user); metadata2.Inlines.Add(new Bold(new Run(u.name))); metadata2.Inlines.Add(" " + configurations.contribution_comment_date); metadata2.Inlines.Add(new Bold(new Run(date1 + " " + date2))); } //metadata.Inlines.Add(new LineBreak()); //location if (the_contribution.location_id != 0) { metadata3.Inlines.Add(configurations.contribution_comment_location); metadata3.Inlines.Add(new Bold(new Run(the_contribution.Location.name))); } else { if (configurations.show_empty_metadata) metadata3.Inlines.Add("Location not specified."); else { metadata3.Visibility = System.Windows.Visibility.Collapsed; should_show_metadata3 = false; } } //metadata.Inlines.Add(new LineBreak()); //tags if (the_contribution.tags != "") { metadata4.Inlines.Add(configurations.contribution_comment_tag); metadata4.Inlines.Add(new Bold(new Run(the_contribution.tags))); } else { if (configurations.show_empty_metadata) metadata4.Inlines.Add(configurations.contribution_comment_tag + "[Empty]"); else { metadata4.Visibility = System.Windows.Visibility.Collapsed; should_show_metadata4 = false; } } //item_generic i = new item_generic(); //i.desc.Visibility = System.Windows.Visibility.Collapsed; //i.top_panel.Visibility = System.Windows.Visibility.Collapsed; //i.content.Text = comment; //i.BorderBrush = Brushes.Gray; //i.BorderThickness = new Thickness(0, 0, 0, 1); //i.Margin = new Thickness(5, 7, 5, 0); //this.comments_listbox.populator.initial_item = i; }
/// ------------------------------------------------------------------------------------ private Contribution GetContributionFromRow(int rowIndex) { var row = _grid.Rows[rowIndex]; var contribution = new Contribution { ContributorName = row.Cells["name"].Value as string, Role = _model.OlacRoles.FirstOrDefault(o => o.Name == row.Cells["role"].Value as string), Comments = row.Cells["comments"].Value as string }; if (row.Cells["date"].Value != null) contribution.Date = (DateTime)row.Cells["date"].Value; return contribution; }
/// ------------------------------------------------------------------------------------ private bool GetIsValidContribution(Contribution contribution) { if (ValidatingContributor == null) return true; var args = new CancelEventArgs(false); ValidatingContributor(this, contribution, args); return !args.Cancel; }
public void deleteContribution(Contribution c, int projectID) { using (var db = new PortfolioUnleashedContext()) { db.Projects.Include("Contributions").Include(p => p.Contributions.Select(co => co.ContributionMedia)).FirstOrDefault(u => u.Id == projectID) .Contributions.Remove(db.Contributions.Where(con => con.ProjectId == projectID && con.UserId == c.UserId).FirstOrDefault()); if (db.ContributionMediums.Any(co => co.UserId == c.UserId && co.ProjectId == projectID)) //Remove all media for contribution { foreach (ContributionMedium cm in db.ContributionMediums.Where(co => co.UserId == c.UserId && co.ProjectId == projectID)) { db.ContributionMediums.Remove(cm); } } db.Contributions.Remove(db.Contributions.Where(cb => cb.UserId == c.UserId && cb.ProjectId == c.ProjectId).FirstOrDefault()); //Remove the contribution db.SaveChanges(); if (db.Projects.Include("Contributions").FirstOrDefault(proj => proj.Id == projectID).Contributions.Count <= 0)//If no contributions remaining { deleteProjectCompletely(db.Projects.Include("Contributions").FirstOrDefault(prod => prod.Id == projectID)); } else if(db.Users.Include("ProjectPermissions").FirstOrDefault(user => user.Id == c.UserId).ProjectPermissions.Any(proj => proj.IsProjectMaster == true)) //Contributing user was a project editor { if (!db.Users.Include("ProjectPermissions").Any(user => (user.ProjectPermissions.Any(proj => (proj.UserId != c.UserId && proj.ProjectId == projectID && proj.IsProjectMaster == true))))) //If no remaining contributing users are project editors { int selectedUserToPromote = db.Projects.Include("Contributions").FirstOrDefault(proj => proj.Id == projectID).Contributions.FirstOrDefault(cont => cont.UserId != null).UserId; db.Users.Include("ProjectPermissions").FirstOrDefault(user => user.Id == selectedUserToPromote).ProjectPermissions.FirstOrDefault(perm => perm.ProjectId == projectID).IsProjectMaster = true; } } if(db.ProjectPermissions.Any(perm => perm.UserId == c.UserId && perm.ProjectId == projectID)) { db.Projects.Include("ProjectPermissions").Where(pr => pr.Id == projectID).FirstOrDefault().ProjectPermissions .Remove(db.ProjectPermissions.Include("Project").Include("User").Where(perm => perm.UserId == c.UserId && perm.ProjectId == projectID).FirstOrDefault()); } db.SaveChanges(); } }
public collection_item create_collection_item_from_contribution(Contribution c) { collection_item ci = new collection_item(); ci._contribution = c; int i = c.id; if (c.media_url == null) return ci; string fname = c.media_url; string ext = fname.Substring(fname.Length - 4, 4); ext = ext.ToLower(); if (ext == ".jpg" || ext == ".bmp" || ext == ".png") ci.is_image = true; if (ext == ".wmv" || ext == ".mpg" || ext == "mpeg" || ext == ".avi" || ext == ".mp4" || ext == ".3gp" || ext == ".mov") ci.is_video = true; if (ext == ".wav" || ext == ".mp3") ci.is_audio = true; if (!window_manager.thumbnails.ContainsKey(i)) { if (!window_manager.downloaded_contributions.Contains(i)) { bool result = file_manager.download_file_from_googledirve(c.media_url, i); if (result) window_manager.downloaded_contributions.Add(i); } ImageSource img = null; if (ci.is_image) img = configurations.GetThumbnailFromImage(i.ToString() + ext, configurations.thumbnail_pixel_height); if (ci.is_video) img = configurations.GetThumbnailFromVideo(i.ToString() + ext, configurations.thumbnail_video_span, configurations.thumbnail_pixel_height); if (ci.is_audio) img = configurations.img_sound_image_pic; if (img == null) return ci; if (!window_manager.thumbnails.ContainsKey(i)) { // save the thumbnail try { BitmapSource bs = img as BitmapSource; if (!ci.is_audio) { configurations.SaveThumbnail(bs, i.ToString()); } img = new BitmapImage(new Uri(configurations.GetAbsoluteThumbnailPath() + i.ToString() + ".jpg")); img.Freeze(); window_manager.thumbnails.Add(i, img); } catch (Exception) { } // not a problem } } return ci; }
private bool SubmitTransaction() { if(!Convert.ToBoolean(this.TestModeSetting)){ try { ContributionFundCollection selectedFundCollection = this.GetSelectedFundCollection(); decimal totalAmount = Convert.ToDecimal(this.hfTotalContribution.Value); bool result; if (selectedFundCollection.TotalFundAmount != totalAmount) { this.DisplayError("There appears to be a problem with the Funds you selected. Please return to the selection screen and review your choices."); result = false; return result; } StringBuilder stringBuilder = new StringBuilder(); if (this.CommentCaptionSetting == string.Empty) { using (List<ContributionFund>.Enumerator enumerator = selectedFundCollection.GetEnumerator()) { while (enumerator.MoveNext()) { ContributionFund current = enumerator.Current; stringBuilder.AppendFormat("F{0}:{1} ", current.FundId.ToString(), current.Amount.ToString("C2")); } goto IL_F3; } } stringBuilder.Append(this.tbComment.Text); IL_F3: GatewayAccount gatewayAccount; string accountNumber; if (rblPaymentMethod.SelectedValue == "CC") { gatewayAccount = this.ccGatewayAcct; accountNumber = this.MaskAccountNumber(this.tbCCNumber.Text); } else { gatewayAccount = this.achGatewayAcct; accountNumber = this.MaskAccountNumber(this.tbAccountNumber.Text); } Transaction transaction = null; if (gatewayAccount.RequiresPaymentGateway) { string confirmationID = this.hfConfirmationID.ToString(); gatewayAccount.ProcessorClass.PaymentFrequency = PaymentFrequency.One_Time; if (gatewayAccount.Authorize(confirmationID)) { transaction = gatewayAccount.Transaction; transaction.PersonId = this._person.PersonID; } } else { if (rblPaymentMethod.SelectedValue == "CC") { if (gatewayAccount.Authorize(TransactionType.Sale, this.tbCCNumber.Text, this.tbCCCIN.Text, this.ddlExpMonth.SelectedValue, this.ddlExpYear.SelectedValue, -1, this._person.PersonID, this._person.FirstName, this._person.FirstName, this._person.LastName, this._person.PrimaryAddress.StreetLine1, this._person.PrimaryAddress.City, this._person.PrimaryAddress.State, this._person.PostalCode, this._person.Phones.FindByType(276).ToString(), this._person.Emails.FirstActive, totalAmount, stringBuilder.ToString(), DateTime.MinValue, PaymentFrequency.One_Time, 0, this._validateCardNumber)) { transaction = gatewayAccount.Transaction; } } else { if (gatewayAccount.AuthorizeACH(TransactionType.Sale, this.tbAccountNumber.Text.Trim(), this.tbRoutingNumber.Text.Trim(), ddlAccountType.Items[0].Selected, this._person.PersonID, this._person.FirstName, this._person.FirstName, this._person.LastName, this._person.PrimaryAddress.StreetLine1, this._person.PrimaryAddress.City, this._person.PrimaryAddress.State, this._person.PrimaryAddress.PostalCode, this._person.Phones.FindByType(276).ToString(), this._person.Emails.FirstActive, totalAmount, stringBuilder.ToString(), DateTime.MinValue, PaymentFrequency.One_Time, 0)) { transaction = gatewayAccount.Transaction; } } } if (transaction != null) { transaction.Save(this._person.FullName); if (!transaction.Success) { this.DisplayError("Authorization of your information failed for the following reason(s):", gatewayAccount.Messages); result = false; return result; } this.curTrans = transaction; string str = "Online Giving"; if (base.CurrentOrganization.Settings["GivingBatchName"] != null) { str = base.CurrentOrganization.Settings["GivingBatchName"]; } BatchType batchType = Batch.GetBatchType(transaction.PaymentMethod.Guid); Batch batch = new Batch(base.CurrentOrganization.OrganizationID, true, str + " " + Enum.GetName(typeof(BatchType), batchType), transaction.TransactionDate, batchType, gatewayAccount.GatewayAccountId, this._person.FullName); batch.VerifyAmount += transaction.TransactionAmount; batch.Save(this._person.FullName); Contribution contribution = new Contribution(); contribution.PersonId = transaction.PersonId; contribution.TransactionId = transaction.TransactionId; contribution.BatchId = batch.BatchId; contribution.ContributionDate = transaction.TransactionDate; contribution.CurrencyAmount = transaction.TransactionAmount; contribution.TransactionNumber = transaction.TransactionDetail; contribution.CurrencyType = transaction.PaymentMethod; contribution.AccountNumber = transaction.RepeatingPayment.AccountNumber; contribution.ContributionFunds = selectedFundCollection; contribution.Memo = stringBuilder.ToString(); contribution.Save(this._person.FullName); this.ConfirmationNumber = "Confirmation Number: " + contribution.TransactionNumber; try { OnlineGivingContribution onlineGivingContribution = new OnlineGivingContribution(); onlineGivingContribution.Send(base.CurrentOrganization, transaction, selectedFundCollection, accountNumber, this.tbEmail.Text); goto IL_B29; } catch (Exception) { goto IL_B29; } } this.DisplayError("Authorization of your information failed for the following reason(s):", gatewayAccount.Messages); result = false; return result; IL_B29: base.Session.Clear(); } catch (Exception inner) { throw new ArenaApplicationException("Error occurred during Authorization", inner); } } return true; }
public static Contribution CreateTestContribution() { Contribution contribution = new Contribution() { Body = "First Item Body", ModerationStatus = CommentStatus.Hidden.NotHidden, PostIndex = 0, SiteName = "h2g2", SiteType = BBC.Dna.Sites.SiteType.Blog, FirstSubject = "Test Instance Source Title", Subject = "Test Instance Sub Title", Timestamp = new DateTimeHelper(DateTime.Now), Title = "Test Instance Title" }; return contribution; }
public ActionResult EditContribution(VMContribution model) { int projectId = int.Parse(Request.Form["ProjectId"]); int userId = int.Parse(Request.Form["UserId"]); Contribution contribution = new Contribution(); if (PersonalContributionVerified(out contribution, userId)) { contribution.UserId = userId; contribution.ProjectId = projectId; if (db.retrieveProject(projectId).Contributions.Any(c => c.UserId == userId && c.ProjectId == projectId)) { db.updateContribution(contribution, projectId); if (contribution.ContributionMedia != null && contribution.ContributionMedia.Count > 0) { foreach (ContributionMedium cm in contribution.ContributionMedia) { if (db.retrieveContribution(userId, projectId).ContributionMedia.Any(m => m.Id == cm.Id)) { if (string.IsNullOrEmpty(cm.Caption) && string.IsNullOrEmpty(cm.Link)) { db.removeContributionMedium(cm); } else { db.updateContributionMedium(cm); } } else { db.addContributionMedium(cm, userId, projectId); } } } } else { db.addContribution(contribution, projectId); } return RedirectToAction("ProjectCatalog", routeValues: new { id = userId }); } contribution.UserId = userId; contribution.ProjectId = projectId; VMContribution contrib = new VMContribution(contribution); return View(contrib); }
public ActionResult ProjectCreateEdit(VMEditingProject model) { bool isValidInput = true; List<ProjectMedium> projectMedia = new List<ProjectMedium>(); if (!AllProjectMediaVerified(out projectMedia)) { isValidInput = false; } List<Contribution> contributions = new List<Contribution>(); if (!AllContributionsVerified(out contributions)) { isValidInput = false; } Contribution personalContribution = new Contribution(); if(!PersonalContributionVerified(out personalContribution, model._currentUserId)) { isValidInput = false; } if (isValidInput && ModelState.IsValid) { int currentUserId = WebSecurity.CurrentUserId; string selectedTemplate = Request.Form.GetValues("Template").FirstOrDefault(); int template = (int)((ProjectTemplate)Enum.Parse(typeof(ProjectTemplate), selectedTemplate)); string selectedContributionSetting = Request.Form.GetValues("ContributionSetting").FirstOrDefault(); int setting = (int)((ContributionSetting)Enum.Parse(typeof(ContributionSetting), selectedContributionSetting)); int projectId = int.Parse(Request.Form.GetValues("Id").FirstOrDefault()); Project p = db.retrieveProject(projectId); bool newProject = true; #region Creating new project properties if (p == null)//Creating { p = new Project(); personalContribution.UserId = currentUserId; p.Title = model.Title; p.Description = model.Description; p.Template = template; p.CollaborationSetting = setting; foreach (Contribution c in contributions) { c.UserId = db.retrieveUserByEmail(c.User.Email).Id; c.User = null; } p.Contributions = contributions; personalContribution.User = null; if (!string.IsNullOrEmpty(personalContribution.Title)) { p.Contributions.Add(personalContribution); } else { p.Contributions.Add(new Contribution(){ UserId = currentUserId}); } p.ProjectMedia = projectMedia; p.ProjectPermissions.Add(new ProjectPermission() { UserId = currentUserId, IsProjectEditor = true, IsProjectMaster = true }); } #endregion #region Editing existing project properties else //editing { newProject = false; p.Title = model.Title; p.Description = model.Description; p.Template = template; p.CollaborationSetting = setting; db.updateProject(p); foreach (Contribution c in contributions) { if (c.ProjectId != projectId)//new contribution entry { c.UserId = db.retrieveUserByEmail(c.User.Email).Id; c.User = null; c.ProjectId = projectId; new NotificationController().CollaborationAddition(WebSecurity.CurrentUserId, c.UserId, projectId); db.addContribution(c, projectId); } } foreach (ProjectMedium m in projectMedia) { ProjectMedium dm = db.retrieveProjectMedium(m.Id); if (dm == null)//medium doesn't exist in project { db.addProjectMedium(m, projectId); } else { if (string.IsNullOrEmpty(m.Caption) && string.IsNullOrEmpty(m.Link))//existed, wants to remove { db.removeProjectMedium(dm); } else { dm.Caption = m.Caption; dm.Link = m.Link; dm.MediumType = m.MediumType; db.updateProjectMedium(dm); } } } #region personal Contribution personalContribution.ProjectId = projectId; personalContribution.User = null; if (!p.Contributions.Any(c=> c.UserId == currentUserId))//didn't have personal contribution { if (string.IsNullOrEmpty(personalContribution.Title)) { db.addContribution(new Contribution() { UserId = currentUserId }, projectId); } else { db.addContribution(personalContribution, projectId); } } else //had personal contribution { Contribution existing = db.retrieveContribution(currentUserId, projectId); existing.Title = personalContribution.Title; existing.Description = personalContribution.Description; foreach (ContributionMedium m in personalContribution.ContributionMedia) { if (existing.ContributionMedia.Any(me => me.Id == m.Id))//Contribution has that medium { if (string.IsNullOrEmpty(m.Link))//blanked out medium { existing.ContributionMedia.Remove(existing.ContributionMedia.Where(me => me.Id == m.Id).First()); db.removeContributionMedium(m); } else { ContributionMedium med = existing.ContributionMedia.Where(me => me.Id == m.Id).First(); med.Caption = m.Caption; med.Link = m.Link; med.MediumType = m.MediumType; db.updateContributionMedium(med); } } else { db.addContributionMedium(m, projectId, currentUserId); } } db.updateContribution(existing, projectId); } #endregion } #endregion #region Adding quick contact collaborators List<string> keys = Request.Form.AllKeys.Where(k => k.Contains("AddBox")).ToList(); if (keys != null && keys.Count > 0) { foreach (string key in keys) { int quickContactId = int.Parse(key.Substring(0, key.IndexOf("AddBox"))); bool addAsCollab = Request.Form.GetValues(key).FirstOrDefault().Equals("true"); if (addAsCollab)//Box was checked { if (!p.Contributions.Any(c => c.UserId == quickContactId))//That contact isn't already a collaborator { p.Contributions.Add(new Contribution() { UserId = quickContactId }); if (!newProject) { db.addContribution(new Contribution() { UserId = quickContactId }, projectId); new NotificationController().CollaborationAddition(WebSecurity.CurrentUserId, quickContactId, projectId); } } } } } #endregion if (newProject) { db.addProject(p); foreach (Contribution c in p.Contributions.Where(c=>c.UserId != WebSecurity.CurrentUserId)) { new NotificationController().CollaborationAddition(WebSecurity.CurrentUserId, c.UserId, p.Id); } } return RedirectToAction("ProjectCatalog", new { id = currentUserId }); } int projId = int.Parse(Request.Form.GetValues("Id").FirstOrDefault()); Project proj = new Project(); proj.Id = projId; proj.Title = model.Title; proj.ProjectMedia = projectMedia; proj.Contributions = contributions; VMEditingProject vmproj = new VMEditingProject(proj, null, model._currentUserId) { EditingCollaborators = model.EditingCollaborators,PersonalContribution = new VMContribution(personalContribution)}; return View(new VMEditingProject()); }
private bool PersonalContributionVerified(out Contribution personalContribution, int currentUserId) { bool isValidInput = true; personalContribution = new Contribution(); List<ContributionMedium> contributionMedia = new List<ContributionMedium>(); if (!AllContributionMediaVerified(out contributionMedia)) { isValidInput = false; } personalContribution.ContributionMedia = contributionMedia; string description = Request.Form.GetValues("PersonalContribution.Description").FirstOrDefault(); string title = Request.Form.GetValues("PersonalContribution.Title").FirstOrDefault(); string[] entry = new string[] { description, title }; if (!allAreNullOrEmpty(entry)) { if (someAreNullOrEmpty(entry)) { isValidInput = false; ModelState.AddModelError("", "If you add personal contribution details, you must enter both your Position Title and a Contribution Description."); } personalContribution.Title = title; personalContribution.Description = description; personalContribution.UserId = currentUserId; personalContribution.User = db.retrieveUser(currentUserId); } else //if description and title empty but they added media { if (contributionMedia.Count > 0) { isValidInput = false; ModelState.AddModelError("", "If you add media to your personal contribution for the project, you must also enter a Title and Description for that contribution."); } } return isValidInput; }
private bool AllContributionsVerified(out List<Contribution> contributions) { bool isValidInput = true; contributions = new List<Contribution>(); string[] contributionProjectIds = Request.Form.GetValues("Contribution.ProjectId"); string[] contributionEmails = Request.Form.GetValues("Contribution.Email"); for (int i = 0; i < contributionProjectIds.Count(); i++) { string[] entryInputs = new string[] { contributionProjectIds[i], contributionEmails[i] }; if (!allAreNullOrEmpty(entryInputs) && !string.IsNullOrEmpty(contributionEmails[i])) { PortfolioUnleashed.User userToAdd = db.retrieveUserByEmail(contributionEmails[i]); if (userToAdd == null) { isValidInput = false; ModelState.AddModelError("", "There is no registered User with the email address " + contributionEmails[i] + ". They must be registered with the site to be added as a collaborator."); } Contribution c = new Contribution(); c.User = new User() { Email = contributionEmails[i] }; c.ProjectId = int.Parse(contributionProjectIds[i]); contributions.Add(c); } } return isValidInput; }
public static void SendEmail(Contribution contrib) { var smtp = new SmtpClient("localhost"); var subject = string.Format("Thank you for donating to {0}, redeem your Kudos now! :-)", contrib.IsSpringContribution ? "Spring/Zero-K" : "Zero-K"); var body = string.Format( "Hi {0}, \nThank you for donating to {1}\nYou can now redeem Kudos - special reward for Zero-K by clicking here: {2} \n (Please be patient Kudos features for the game will be added in the short future)\n\nWe wish you lots of fun playing the game and we are looking forward to meet you in game!\nThe Zero-K team", contrib.Name.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(), contrib.IsSpringContribution ? "the Spring project and Zero-K" : "Zero-K and Spring project", GetCodeLink(contrib.RedeemCode)); smtp.Send(new MailMessage(GlobalConst.TeamEmail, contrib.Email, subject, body)); }
Contribution AddPayPalContribution(ParsedData parsed) { try { if ((parsed.Status != "Completed" && parsed.Status != "Cleared") || parsed.Gross <= 0) return null; // not a contribution! double netEur; double grossEur; if (parsed.Currency == "EUR") { netEur = parsed.Net; grossEur = parsed.Gross; } else { netEur = ConvertToEuros(parsed.Currency, parsed.Net); grossEur = ConvertToEuros(parsed.Currency, parsed.Gross); } int? accountID, jarID; TryParseItemCode(parsed.ItemCode, out accountID, out jarID); Contribution contrib; using (var db = new ZkDataContext()) { Account acc = null; ContributionJar jar; if (jarID == null) jar = db.ContributionJars.FirstOrDefault(x => x.IsDefault); else jar = db.ContributionJars.FirstOrDefault(x => x.ContributionJarID == jarID); if (accountID != null) acc = db.Accounts.Find(accountID.Value); if (!string.IsNullOrEmpty(parsed.TransactionID) && db.Contributions.Any(x => x.PayPalTransactionID == parsed.TransactionID)) return null; // contribution already exists var isSpring = !parsed.ItemCode.StartsWith("ZK") || jar.IsDefault; contrib = new Contribution() { AccountByAccountID = acc, Name = parsed.Name, Euros = grossEur, KudosValue = (int)Math.Round(grossEur*GlobalConst.EurosToKudos), OriginalAmount = parsed.Gross, OriginalCurrency = parsed.Currency, PayPalTransactionID = parsed.TransactionID, ItemCode = parsed.ItemCode, Time = parsed.Time, EurosNet = netEur, ItemName = parsed.ItemName, Email = parsed.Email, RedeemCode = Guid.NewGuid().ToString(), IsSpringContribution = isSpring, ContributionJar = jar }; db.Contributions.Add(contrib); db.SaveChanges(); if (acc != null) acc.Kudos = acc.KudosGained - acc.KudosSpent; db.SaveChanges(); // technically not needed to sent when account is known, but perhaps its nice to get a confirmation like that SendEmail(contrib); NewContribution(contrib); } return contrib; } catch (Exception ex) { Trace.TraceError("Error processing payment: {0}", ex); Error(ex.ToString()); return null; } }
protected void btnSave_Click(object sender, EventArgs e) { using (FinanceManagerDataContext db = new FinanceManagerDataContext()) { LoanWebApplication4.CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault(); double InvsetmentAmount = double.Parse(PrincipalTextBox.Text); double MaturedInvestmentAmount;// = double.Parse(lblTotalAmount.Text); // double interestRate = Convert.ToDouble(InterestTextBox.Text); //Convert.ToDouble(cProfile.CompoundInterestRate.Value); LoanDuration _loanDuration = db.LoanDurations.FirstOrDefault(l => l.LoanDurationId == Convert.ToInt32(cboLoanDurationType.SelectedValue)); if (_loanDuration == null) return; //int period = int.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value; decimal period = decimal.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value / 12; //LoanPreset _loanPreset = db.LoanPresets.First(l => l.LoanPresetId == Convert.ToInt32(cboInterestDuration.SelectedValue)); //double interestRate = Utils.CalculateInterestRateByDuration(_loanPreset.InsterestRate.Value, period); //double interestRate = Utils.CalculateInterestRateByDuration(decimal.Parse(InterestTextBox.Text), period); double interestRate = double.Parse(InterestTextBox.Text); // int period = int.Parse(DurationTextBox.Text); int compoundType = cProfile.CompoundFrequency.Value; //using repayment frequency for contribution frequency //RepaymentFrequency _repaymentFrequency = db.RepaymentFrequencies.FirstOrDefault(r => r.RepaymentFrequencyId == int.Parse(RepaymentFrequencyDropdownList.SelectedValue)); double amount; if (InterestTypeDropDownList.SelectedValue == "1") //compound { amount = Utils.calculateCompoundInterest(InvsetmentAmount, interestRate, period, Utils.GetCompoundType(compoundType)); } else //2 for simple interest { amount = Utils.calculateSimpleInterest(InvsetmentAmount, interestRate, period); } decimal _originalInvestmentAmount = 0; //get an existing investment or create a new one Investment newInvestment; if (Request.QueryString["InvId"] != null) { newInvestment = db.Investments.FirstOrDefault(i => i.InvestmentID == Convert.ToInt32(Request.QueryString["InvId"])); _originalInvestmentAmount = newInvestment.InvestmentAmount.Value; } else { newInvestment = new Investment(); } //set invementType to 3 for fixed deposit investment newInvestment.InvestmentTypeId = 3; //newLoan.ActualRepaymentEndDate = DateTime.Today.AddMonths(period); // newLoan.Amount = (decimal)amount; if (Request.QueryString["mid"] != null) { newInvestment.MemberID = Convert.ToInt32(Request.QueryString["mid"]); } else { newInvestment.GroupId = Convert.ToInt32(Request.QueryString["gid"]); } newInvestment.IsDeleted = false; newInvestment.InvestmentAmount = (decimal)InvsetmentAmount; //newInvestment.ContributionFrequencyId = _repaymentFrequency.RepaymentFrequencyId; newInvestment.IsMatured = false; newInvestment.InsterstRate = (decimal)interestRate; newInvestment.Duration = decimal.Parse(DurationTextBox.Text); newInvestment.InterestTypeId = Convert.ToInt32(InterestTypeDropDownList.SelectedValue); //newLoan.payWithContribution = false; newInvestment.InvestmentCalculationStartDate = DateWebUserControl1.DtSelectedDate; newInvestment.IsActive = true; newInvestment.InterestDurationTypeID = Convert.ToInt32(cboLoanDurationType.SelectedValue); //variable to hold period for the calculation of MaturityDate calculation int tempPeriod; tempPeriod = int.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value; //start calculation from the LoanCalculationStartDate specified newInvestment.MaturityDate = newInvestment.InvestmentCalculationStartDate.Value.AddMonths(tempPeriod); //if the expected repayment end date falls on a weekend, move it to a working if (newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Saturday) { newInvestment.MaturityDate = newInvestment.MaturityDate.Value.AddDays(2); } else if (newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Sunday) { newInvestment.MaturityDate = newInvestment.MaturityDate.Value.AddDays(1); } newInvestment.DurationTypeId = Convert.ToInt32(cboLoanDurationType.SelectedValue); //newLoan.RawDurationEntered = DurationTextBox.Text; newInvestment.InvestmentCalculationStartDate = DateTime.Now; TimeSpan tSpan = newInvestment.MaturityDate.Value - newInvestment.InvestmentCalculationStartDate.Value;// -DateTime.Today; double numberOfDaysBetweenExpectedEndDateAndNow = tSpan.TotalDays; //int xx = (int)numberOfDaysBetweenExpectedEndDateAndNow / _repaymentFrequency.NumberOfDays.Value; //int numberOfDaysBetweenExpectedEndDateAndNow = 30 * period; //assuming there are 30 days in a month //decimal xx = numberOfDaysBetweenExpectedEndDateAndNow / _repaymentFrequency.NumberOfDays.Value; //newInvestment.ContributionFreqAmount = ((decimal)newInvestment.InvestmentAmount / xx); //maturity amount MaturedInvestmentAmount = amount; newInvestment.CreatedBy = this.User.Identity.Name; newInvestment.MaturedAmount = (decimal)amount; //set invementType to 3 for fixed deposit investment newInvestment.InvestmentTypeId = 3; Parameter prm = db.Parameters.FirstOrDefault(); //increase receipt number by one prm.ReceiptNumber++; if (Request.QueryString["InvId"] != null) { newInvestment.ModifiedDate = DateTime.Now; newInvestment.ModifiedBy = HttpContext.Current.User.Identity.Name; //audit Utils.logAction("Edit", newInvestment); db.SubmitChanges(); //make contibution if the original amount is less than the new amount otherwise make a withrawal if (newInvestment.InvestmentAmount > _originalInvestmentAmount) { //make contribution Contribution _contribution = new Contribution() { ContributionAmount = newInvestment.InvestmentAmount - _originalInvestmentAmount, ContributionBy = "Self", ContributionAmountInWords = Utils.ConvertMoneyToText(newInvestment.InvestmentAmount.ToString()), Description = "Fixed deposit contribution as a result of a edit action on an the investment", ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0'), RecievedBy = User.Identity.Name, InvestmentId = newInvestment.InvestmentID, PaymentMethodId = PaymentMethodWebUserControl1.PaymentTypeID, ChequeNumber = PaymentMethodWebUserControl1.ChequeNumber, IsDeleted = false, CreatedDate = DateWebUserControl1.DtSelectedDate, CreatedBy = HttpContext.Current.User.Identity.Name }; _contribution.CreatedDate = DateWebUserControl1.DtSelectedDate; db.Contributions.InsertOnSubmit(_contribution); db.SubmitChanges(); //audit Utils.logAction("Insert", _contribution); } else if (newInvestment.InvestmentAmount < _originalInvestmentAmount) { //make withdrawal MemberWithdrawal _memberWithdrawal = new MemberWithdrawal() { CreatedBy = HttpContext.Current.User.Identity.Name, DateCreated = DateTime.Now, IsDeleted = false, WithdrawalAmount = _originalInvestmentAmount - newInvestment.InvestmentAmount , WithdrawnBy = "Self", //ContributionAmountInWords = Utils.ConvertMoneyToText(newInvestment.InvestmentAmount.ToString()), Narration = "Fixed deposit withdrawal as a result of a edit action on an the investment", //ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0'), WithdrawalIssuedByUserName = User.Identity.Name, InvestmentID = newInvestment.InvestmentID }; db.MemberWithdrawals.InsertOnSubmit(_memberWithdrawal); db.SubmitChanges(); //audit Utils.logAction("Insert", _memberWithdrawal); } } else { newInvestment.CreatedDate = DateTime.Now; db.Investments.InsertOnSubmit(newInvestment); db.SubmitChanges(); //audit Utils.logAction("Insert", newInvestment); //make initial contribution if fixed deposit investment is a new one //add contribution since it a fixed deposit Contribution _contribution = new Contribution() { ContributionAmount = newInvestment.InvestmentAmount, ContributionBy = "Self", ContributionAmountInWords = Utils.ConvertMoneyToText(newInvestment.InvestmentAmount.ToString()), Description = "Fixed deposit contribution", ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0'), RecievedBy = User.Identity.Name, InvestmentId = newInvestment.InvestmentID, IsDeleted = false, CreatedDate = DateWebUserControl1.DtSelectedDate, CreatedBy = HttpContext.Current.User.Identity.Name }; db.Contributions.InsertOnSubmit(_contribution); db.SubmitChanges(); //audit Utils.logAction("Insert", _contribution); } //ResponseHelper.Redirect(this.Response, "ContributionReceipt.aspx?cid=" + _contribution.ContributionId.ToString() + "&mid=" + _contribution.Investment.MemberID, "_blank", "menubar=0,width=100,height=100"); if (Request.QueryString["mid"] != null) { Response.Redirect("FixedDepositInvestmentStatement.aspx?invID=" + newInvestment.InvestmentID + "&mid=" + Request.QueryString["mid"]); } else if(Request.QueryString["gid"] != null) { Response.Redirect("FixedDepositInvestmentStatement.aspx?invID=" + newInvestment.InvestmentID + "&gid=" + Request.QueryString["gid"]); } } }
/// <summary>Processes and URL and gets the data for each mail item in a mail list</summary> /// <param name="url">The Mail list URL to scan</param> /// <returns>A list of mail items</returns> private IEnumerable<Contribution> ProcessUrl(Uri url) { var returnValue = new List<Contribution>(); string responseData; var webRequest = WebRequest.CreateHttp(url); var httpResponse = (HttpWebResponse)webRequest.GetResponse(); var stream = httpResponse.GetResponseStream(); if (null == stream) { return returnValue; } using (var responseReader = new StreamReader(stream)) { responseData = responseReader.ReadToEnd(); } var mailListItem = MailListIdentifier.Match(responseData); var dateMailMatches = DateMaildentifier.Matches(mailListItem.Groups["messages"].Value); foreach (Match dateMails in dateMailMatches) { var itemsDateString = dateMails.Groups["date"].Value; DateTime itemsDate; if (!DateTime.TryParse(itemsDateString, out itemsDate)) { continue; } var mailItems = dateMails.Groups["mails"].Value; foreach (Match matchedRecord in RecordIdentifier.Matches(mailItems)) { var r = new Contribution { Date = itemsDate, Tracker = new Tracker() {Name = Tracker} }; var mailUri = new Uri(url, matchedRecord.Groups["url"].Value); r.Url = mailUri.AbsoluteUri; r.Author = new Author() { Name = matchedRecord.Groups["author"].Value }; r.Message = HttpUtility.HtmlDecode(matchedRecord.Groups["subject"].Value); string[] emailFullMessage; if(SpecIdentifier.IsMatch(r.Message)) { foreach (var spec in from Match specRecord in SpecIdentifier.Matches(r.Message) select specRecord.Groups["spec"].Value.IsNullOrEmptyOrWhiteSpace("unknown").ToLowerInvariant()) { r.Sha = (r.Url + spec).GetHashSha1(); if (CheckContributionsForSha(r.Sha)) continue; var s = r.DeepClone(); //if it is not in DB then go here emailFullMessage = GetEmailAndFullMessage(mailUri); s.Email = emailFullMessage[0]; SetAuthorEmailOrganization(s); s.Spec = new Spec() { Name = spec }; returnValue.Add(s);//submit record to DB } } else { r.Sha = r.Url.GetHashSha1(); if (CheckContributionsForSha(r.Sha)) { continue; } //if it is not in DB then go here emailFullMessage = GetEmailAndFullMessage(mailUri); r.Email = emailFullMessage[0]; SetAuthorEmailOrganization(r); r.Spec = new Spec() { Name = matchedRecord.Groups["spec"].Value.IsNullOrEmptyOrWhiteSpace("unknown").ToLowerInvariant() }; if(r.Spec.Name.Equals("unknown", StringComparison.InvariantCultureIgnoreCase)) { r.Spec = new Spec() { Name = TrackerData.DetermineIntent(emailFullMessage[1]) }; } //if spec is still unknown don't add it to DB if(!r.Spec.Name.Equals("unknown", StringComparison.InvariantCultureIgnoreCase)) { returnValue.Add(r);//submit record to DB } } } } return returnValue; }
/// <summary>Sets the Author, Email and Organization for the Contribution</summary> /// <param name="r">The current Contribution record to update</param> private static void SetAuthorEmailOrganization(Contribution r) { string organization; if(!string.IsNullOrWhiteSpace(r.Email)) { var nameAndOrganization = TrackerData.GetNameAndOrganization(r.Email); if(!string.IsNullOrWhiteSpace(nameAndOrganization[0]) && string.IsNullOrWhiteSpace(r.Author.Name)) { r.Author.Name = nameAndOrganization[0]; } organization = nameAndOrganization[1]; } else { var emailAndOrganization = TrackerData.GetEmailAndOrganization(r.Author.Name); r.Email = emailAndOrganization[0].ToLowerInvariant(); organization = emailAndOrganization[1]; } r.Author.Email = r.Email.IsNullOrEmptyOrWhiteSpace("unknown"); r.Organization = new Organization() { Name = organization }; }
static void Main(string[] args) { try { BasicHttpBinding binding = new BasicHttpBinding(); EndpointAddress address = new EndpointAddress(new Uri("http://*****:*****@"../../Resources/menu.txt"); foreach (string line in lines) { Console.WriteLine("\t\t" + line); } var keyInfo = new ConsoleKeyInfo(); while (!keyInfo.Key.ToString().Equals("Escape")) { Console.WriteLine("\n\t1: CRUD Person"); Console.WriteLine("\t2: CRUD Event"); Console.WriteLine("\t3: CR Contribution"); Console.WriteLine("\t4: Manage events"); Console.WriteLine("\t5: Manage contributions"); Console.WriteLine("\tEchap: Exit\n"); keyInfo = Console.ReadKey(true); switch (keyInfo.Key.ToString()) { #region CRUD Person case "NumPad1": var keyInfoPerson = new ConsoleKeyInfo(); while (!keyInfoPerson.Key.ToString().Equals("Escape")) { Console.WriteLine("\n\t1: Get all persons"); Console.WriteLine("\t2: Create person"); Console.WriteLine("\t3: Update person"); Console.WriteLine("\t4: Delete person"); Console.WriteLine("\tEchap: Go back\n"); keyInfoPerson = Console.ReadKey(true); switch (keyInfoPerson.Key.ToString()) { // GET ALL PERSONS case "NumPad1": List<Person> persons = new List<Person>(channel.GetAllPersons()); if (persons.Count == 0) { Console.WriteLine("\nNo persons created yet"); } else { foreach (var person in persons) { Console.WriteLine(person.Firstname + " " + person.Lastname + " " + person.Nickname); } } break; // CREATE PERSON case "NumPad2": Person newPerson = new Person(); Console.Write("Firstname: "); newPerson.Firstname = Console.ReadLine(); Console.Write("Lastname: "); newPerson.Lastname = Console.ReadLine(); Console.Write("Nickname: "); newPerson.Nickname = Console.ReadLine(); var createdPerson = channel.CreatePerson(newPerson); if (createdPerson == null) { Console.WriteLine("\nYou have to give a value for all fields, or maybe this person already exists in Database"); } else { Console.WriteLine("\nNew person created: "); Console.WriteLine("Firstname: " + createdPerson.Firstname + "\tLastname: " + createdPerson.Lastname + "\tNickname: " + createdPerson.Nickname); } break; // UPDATE PERSON case "NumPad3": Console.Write("Nickname of the person you want to update: "); string nickname = Console.ReadLine(); Person personToUpdate = channel.GetPersonByNickname(nickname); if (personToUpdate == null) { Console.WriteLine("\nThis person does not exist"); } else { Console.WriteLine("\nPerson to update: "); Console.WriteLine("Firstname: " + personToUpdate.Firstname + "\tLastname: " + personToUpdate.Lastname + "\tNickname: " + personToUpdate.Nickname); Console.WriteLine("\nPlease provide new data (EMPTY VALUE WILL KEEP EXISTING VALUE)"); Console.Write("Firstname: "); string firstname = Console.ReadLine(); personToUpdate.Firstname = firstname.Equals("") ? personToUpdate.Firstname : firstname; Console.Write("Lastname: "); string lastname = Console.ReadLine(); personToUpdate.Lastname = lastname.Equals("") ? personToUpdate.Lastname : lastname; Console.Write("Nickname: "); nickname = Console.ReadLine(); personToUpdate.Nickname = nickname.Equals("") ? personToUpdate.Nickname : nickname; Person updatedPerson = channel.UpdatePerson(personToUpdate); if (updatedPerson == null) { Console.WriteLine("\nThis person already exists in Database"); } else { Console.WriteLine("\nUpdated person: "); Console.WriteLine("Firstname: " + updatedPerson.Firstname + ", Lastname: " + updatedPerson.Lastname + ", Nickname: " + updatedPerson.Nickname); } } break; // DELETE PERSON case "NumPad4": Console.Write("\nNickname of the person you want to delete: "); nickname = Console.ReadLine(); Person personToDelete = channel.GetPersonByNickname(nickname); if (personToDelete == null) { Console.WriteLine("\nThis person does not exist"); } else { bool isDeleted = channel.DeletePerson(personToDelete); if (isDeleted == false) { Console.WriteLine("\nCan't delete this person, maybe already deleted"); } else { Console.WriteLine("\nPerson deleted"); } } break; case "Escape": break; default: Console.WriteLine("\nEnter a valid value"); break; } } break; #endregion #region CRUD Event case "NumPad2": var keyInfoEvent = new ConsoleKeyInfo(); while (!keyInfoEvent.Key.ToString().Equals("Escape")) { Console.WriteLine("\n\t1: Get all events"); Console.WriteLine("\t2: Create event"); Console.WriteLine("\t3: Update event"); Console.WriteLine("\t4: Delete event"); Console.WriteLine("\tEchap: Go back\n"); keyInfoEvent = Console.ReadKey(true); switch (keyInfoEvent.Key.ToString()) { // GET ALL EVENTS case "NumPad1": List<Event> events = new List<Event>(channel.GetAllEvents()); if (events.Count == 0) { Console.WriteLine("\nNo event created yet"); } else { foreach (var eventLoop in events) { Console.WriteLine(eventLoop.Name + " " + eventLoop.Date + " " + eventLoop.Address + " " + eventLoop.Description + " " + eventLoop.Status.ToString() + " " + eventLoop.Type.ToString()); } } break; // CREATE EVENT case "NumPad2": Event eventToCreate = new Event(); Console.Write("Name: "); eventToCreate.Name = Console.ReadLine(); Console.Write("Date (format \"dd/MM/yyyy\"): "); try { eventToCreate.Date = DateTime.ParseExact(Console.ReadLine(), "dd/MM/yyyy", CultureInfo.CurrentCulture); } catch (Exception) { goto default; } Console.Write("Address: "); eventToCreate.Address = Console.ReadLine(); Console.Write("Description: "); eventToCreate.Description = Console.ReadLine(); Console.Write("Status (\"Open\", \"Closed\" or \"Pending\"): "); try { string status = Console.ReadLine(); eventToCreate.Status = (EventStatus)Enum.Parse(typeof(EventStatus), status[0].ToString().ToUpper() + status.Substring(1)); Console.Write("Type (\"Party\" or \"Lunch\"): "); string type = Console.ReadLine(); eventToCreate.Type = (EventType)Enum.Parse(typeof(EventType), type[0].ToString().ToUpper() + type.Substring(1)); } catch (Exception) { goto default; } Event createdEvent = channel.CreateEvent(eventToCreate); if (createdEvent == null) { Console.WriteLine("\nYou have to give a value for all fields, or maybe this name is already taken"); } else { Console.WriteLine("\nNew event created: "); Console.WriteLine(createdEvent.Name + " " + createdEvent.Date + " " + createdEvent.Address + " " + createdEvent.Description + " " + createdEvent.Status.ToString() + " " + createdEvent.Type.ToString()); } break; // UPDATE EVENT case "NumPad3": Console.Write("\nName of the event you want to update: "); string eventName = Console.ReadLine(); Event eventToUpdate = channel.GetEventByName(eventName); if(eventToUpdate == null) { Console.WriteLine("\nThis event does not exist"); } else { Console.WriteLine("\nEvent to update: "); Console.WriteLine(eventToUpdate.Name + " " + eventToUpdate.Date + " " + eventToUpdate.Address + " " + eventToUpdate.Description + " " + eventToUpdate.Status.ToString() + " " + eventToUpdate.Type.ToString()); Console.WriteLine("\nPlease provide new data (EMPTY VALUE WILL KEEP EXISTING VALUE)"); Console.Write("Name: "); eventName = Console.ReadLine(); eventToUpdate.Name = eventName.Equals("") ? eventToUpdate.Name : eventName; Console.Write("Date (format \"dd/MM/yyyy\"): "); try { string newDateString = Console.ReadLine(); eventToUpdate.Date = newDateString.Equals("") ? eventToUpdate.Date : DateTime.ParseExact(newDateString, "dd/MM/yyyy", CultureInfo.CurrentCulture); } catch(Exception) { goto default; } Console.Write("Address: "); string eventAddress = Console.ReadLine(); eventToUpdate.Address = eventAddress.Equals("") ? eventToUpdate.Address : eventAddress; Console.Write("Description: "); string eventDescription = Console.ReadLine(); eventToUpdate.Description = eventDescription.Equals("") ? eventToUpdate.Description : eventDescription; Console.Write("Status (\"Open\", \"Closed\" or \"Pending\"): "); try { string eventStatus = Console.ReadLine(); eventToUpdate.Status = eventStatus.Equals("") ? eventToUpdate.Status : (EventStatus)Enum.Parse(typeof(EventStatus), eventStatus[0].ToString().ToUpper() + eventStatus.Substring(1)); Console.Write("Type (\"Party\" or \"Lunch\"): "); string eventType = Console.ReadLine(); eventToUpdate.Type = eventType.Equals("") ? eventToUpdate.Type : (EventType)Enum.Parse(typeof(EventType), eventType[0].ToString().ToUpper() + eventType.Substring(1)); } catch (Exception) { goto default; } Event updatedEvent = channel.UpdateEvent(eventToUpdate); if (updatedEvent == null) { Console.WriteLine("\nThis event name is already taken"); } else { Console.WriteLine("\nUpdated event: "); Console.WriteLine(updatedEvent.Name + " " + updatedEvent.Date + " " + updatedEvent.Address + " " + updatedEvent.Description + " " + updatedEvent.Status.ToString() + " " + updatedEvent.Type.ToString()); } } break; // DELETE EVENT case "NumPad4": Console.Write("\nName of the event you want to delete: "); eventName = Console.ReadLine(); Event EventToDelete = channel.GetEventByName(eventName); if (EventToDelete == null) { Console.WriteLine("\nThis event does not exist"); } else { bool isDeleted = channel.DeleteEvent(EventToDelete); if (isDeleted == false) { Console.WriteLine("\nCan't delete this event, maybe already deleted"); } else { Console.WriteLine("\nEvent deleted"); } } break; case "Escape": break; default: Console.WriteLine("\nEnter a valid value"); break; } } break; #endregion #region CR Contribution case "NumPad3": var keyInfoContribution = new ConsoleKeyInfo(); while (!keyInfoContribution.Key.ToString().Equals("Escape")) { Console.WriteLine("\n\t1: Get all contributions"); Console.WriteLine("\t2: Create contribution"); Console.WriteLine("\t3: Add contribution to an existing event"); Console.WriteLine("\tEchap: Go back\n"); keyInfoContribution = Console.ReadKey(true); switch (keyInfoContribution.Key.ToString()) { // GET ALL CONTRIBUTIONS case "NumPad1": List<Contribution> contributions = new List<Contribution>(channel.GetAllContributions()); if (contributions.Count == 0) { Console.WriteLine("\nNo contribution created yet"); } else { foreach (var contribution in contributions) { Console.WriteLine(contribution.Name + " " + contribution.Type + " " + contribution.Quantity + " " + contribution.Person.Nickname); } } break; // CREATE CONTRIBUTION case "NumPad2": Contribution newContribution = new Contribution(); Console.Write("Name: "); newContribution.Name = Console.ReadLine(); try { if(channel.GetContributionByName(newContribution.Name) != null) { Console.WriteLine("\nThis contribution name is already used"); throw new Exception(); } Console.Write("Type (\"Money\", \"Food\" or \"Beverage\"): "); var contributionType = Console.ReadLine(); newContribution.Type = (ContributionType)Enum.Parse(typeof(ContributionType), contributionType[0].ToString().ToUpper() + contributionType.Substring(1)); Console.Write("Quantity (ex: \"2L of vodka\"): "); newContribution.Quantity = Console.ReadLine(); Console.Write("Nickname of existing person: "); var contributionPersonNickname = Console.ReadLine(); var contributionPerson = channel.GetPersonByNickname(contributionPersonNickname); if (contributionPerson == null) { throw new Exception(); } newContribution.Person = contributionPerson; var createdContribution = channel.CreateContribution(newContribution); if (createdContribution == null) { Console.WriteLine("\nThis contribution name is already used"); } else { Console.WriteLine("\n" + createdContribution.Name + " " + createdContribution.Type + " " + createdContribution.Quantity + " " + createdContribution.Person.Nickname); } } catch (Exception) { goto default; } break; // ADD CONTRIBUTION TO AN EXISTING EVENT case "NumPad3": try { Console.Write("Contribution's name: "); string contributionName = Console.ReadLine(); var contributionInDb = channel.GetContributionByName(contributionName); if (contributionInDb == null) { Console.WriteLine("\nThis contribution does not exist"); throw new Exception(); } Console.Write("Event's name: "); string eventName = Console.ReadLine(); var eventInDb = channel.GetEventByName(eventName); if (eventInDb == null) { Console.WriteLine("\nThis event does not exist"); throw new Exception(); } var updatedEvent = channel.AddContribution(contributionInDb, eventInDb); if(updatedEvent == null) { Console.WriteLine("\nThis contribution has already been added to an event"); } else { Console.WriteLine("\nContribution added to the event: "); Console.WriteLine(updatedEvent.Name + " " + updatedEvent.Date + " " + updatedEvent.Address + " " + updatedEvent.Description + " " + updatedEvent.Status.ToString() + " " + updatedEvent.Type.ToString()); } } catch (Exception) { goto default; } break; case "Escape": break; default: Console.WriteLine("\nEnter a valid value"); break; } } break; #endregion #region Manage events case "NumPad4": var keyInfoManageEvents = new ConsoleKeyInfo(); while (!keyInfoManageEvents.Key.ToString().Equals("Escape")) { Console.WriteLine("\n\t1: Get event by name"); Console.WriteLine("\t2: Get event(s) by date"); Console.WriteLine("\t3: Get event(s) between two dates"); Console.WriteLine("\t4: Get event(s) by status"); Console.WriteLine("\t5: Get event(s) by type"); Console.WriteLine("\t6: Delete all closed events"); Console.WriteLine("\t7: Update pending events to open"); Console.WriteLine("\t8: Add a person to an open event"); Console.WriteLine("\t9: Get all persons in an open event"); Console.WriteLine("\tEchap: Go back\n"); keyInfoManageEvents = Console.ReadKey(true); switch (keyInfoManageEvents.Key.ToString()) { // GET EVENT BY NAME case "NumPad1": Console.Write("\nEvent's name: "); string eventName = Console.ReadLine(); Event eventInDb = channel.GetEventByName(eventName); if (eventInDb == null) { Console.WriteLine("\nThis event does not exist"); } else { Console.WriteLine(eventInDb.Name + " " + eventInDb.Date + " " + eventInDb.Address + " " + eventInDb.Description + " " + eventInDb.Status.ToString() + " " + eventInDb.Type.ToString()); } break; // GET EVENT(S) BY DATE case "NumPad2": Console.Write("Date (format \"dd/MM/yyyy\"): "); DateTime date = DateTime.ParseExact(Console.ReadLine(), "dd/MM/yyyy", CultureInfo.CurrentCulture); var events = channel.GetEventsByDate(date); if (events.Count() == 0) { Console.WriteLine("\nNo event on this date"); } else { foreach (var event1 in events) { Console.WriteLine("\n" + event1.Name + " " + event1.Date + " " + event1.Address + " " + event1.Description + " " + event1.Status.ToString() + " " + event1.Type.ToString()); } } break; // GET EVENT(S) BETWEEN TWO DATES case "NumPad3": try { Console.Write("Start date (format \"dd/MM/yyyy\"): "); DateTime startDate = DateTime.ParseExact(Console.ReadLine(), "dd/MM/yyyy", CultureInfo.CurrentCulture); Console.Write("End date (format \"dd/MM/yyyy\"): "); DateTime endDate = DateTime.ParseExact(Console.ReadLine(), "dd/MM/yyyy", CultureInfo.CurrentCulture); var eventsResult = channel.GetEventsBetweenTwoDates(startDate, endDate); if (eventsResult.Count() == 0) { Console.WriteLine("\nNo events between these two dates"); } else { foreach (var eventResult in eventsResult) { Console.WriteLine("\n" + eventResult.Name + " " + eventResult.Date + " " + eventResult.Address + " " + eventResult.Description + " " + eventResult.Status.ToString() + " " + eventResult.Type.ToString()); } } } catch (Exception) { goto default; } break; // GET EVENT(S) BY STATUS case "NumPad4": Console.Write("Status (\"Open\", \"Closed\" or \"Pending\"): "); try { string eventStatusSring = Console.ReadLine(); EventStatus eventStatus = (EventStatus)Enum.Parse(typeof(EventStatus), eventStatusSring[0].ToString().ToUpper() + eventStatusSring.Substring(1)); var eventsByStatus = channel.GetEventsByStatus(eventStatus); if (eventsByStatus.Count() == 0) { Console.WriteLine("\nNo event with this status"); } else { foreach (var eventByStatus in eventsByStatus) { Console.WriteLine("\n" + eventByStatus.Name + " " + eventByStatus.Date + " " + eventByStatus.Address + " " + eventByStatus.Description + " " + eventByStatus.Status.ToString() + " " + eventByStatus.Type.ToString()); } } } catch (Exception) { goto default; } break; // GET EVENT(S) BY TYPE case "NumPad5": Console.Write("Type (\"Party\" or \"Lunch\"): "); try { string eventTypeString = Console.ReadLine(); EventType eventType = (EventType)Enum.Parse(typeof(EventType), eventTypeString[0].ToString().ToUpper() + eventTypeString.Substring(1)); var eventsByType = channel.GetEventsByType(eventType); if (eventsByType.Count() == 0) { Console.WriteLine("\nNo event with this type"); } else { foreach (var eventByType in eventsByType) { Console.WriteLine("\n" + eventByType.Name + " " + eventByType.Date + " " + eventByType.Address + " " + eventByType.Description + " " + eventByType.Status.ToString() + " " + eventByType.Type.ToString()); } } } catch (Exception) { goto default; } break; // DELETE ALL CLOSED EVENTS case "NumPad6": if (channel.DeleteClosedEvents() == false) { Console.WriteLine("\nThere was no closed events to delete"); } else { Console.WriteLine("\nClosed events are now deleted"); } break; // UPDATE PENDING EVENTS TO OPEN case "NumPad7": if (channel.UpdatePendingEvents() == false) { Console.WriteLine("\nThere was no pending events"); } else { Console.WriteLine("\nPending events are now open"); } break; // ADD PERSON TO AN OPEN EVENT case "NumPad8": try { Console.Write("Person's nickname: "); string nickname = Console.ReadLine(); var personToAddToEvent = channel.GetPersonByNickname(nickname); if (personToAddToEvent == null) { throw new Exception(); } Console.Write("Event's name: "); string eventNameString = Console.ReadLine(); var eventTarget = channel.GetEventByName(eventNameString); if (eventTarget == null) { throw new Exception(); } if (channel.AddPersonToOpenEvent(eventTarget, personToAddToEvent) == false) { Console.WriteLine("\nThis event is not open, or this person has already been added to it"); } else { Console.WriteLine("\nPerson added to this event"); } } catch (Exception) { goto default; } break; // GET ALL PERSONS IN AN OPEN EVENT case "NumPad9": try { Console.Write("Event's name: "); var eventNameString2 = Console.ReadLine(); var event2 = channel.GetEventByName(eventNameString2); if (event2 == null) { throw new Exception(); } var persons = channel.GetAllPersonsFromOpenEvent(event2); if (persons == null) { Console.WriteLine("\nThis event is not Open"); } else if (persons.Length == 0) { Console.WriteLine("\nNobody in this event for the moment"); } else { foreach (var person in persons) { Console.WriteLine(person.Firstname + " " + person.Lastname + " " + person.Nickname); } } } catch (Exception) { goto default; } break; case "Escape": break; default: Console.WriteLine("\nEnter a valid value"); break; } } break; #endregion #region Manage Contributions case "NumPad5": var keyInfoManageContributions = new ConsoleKeyInfo(); while (!keyInfoManageContributions.Key.ToString().Equals("Escape")) { Console.WriteLine("\n\t1: Get all contributions of an event"); Console.WriteLine("\t2: Get all contributions of a person for all events"); Console.WriteLine("\t3: Delete all contribution of a person for all open events"); Console.WriteLine("\tEchap: Go back\n"); keyInfoManageContributions = Console.ReadKey(true); switch (keyInfoManageContributions.Key.ToString()) { // GET ALL CONTRIBUTIONS OF AN EVENT case "NumPad1": try { Console.Write("Event's name: "); var eventNameString2 = Console.ReadLine(); var event2 = channel.GetEventByName(eventNameString2); if (event2 == null) { throw new Exception(); } var contributions = channel.GetAllContributionsFromEvent(event2); if (contributions.Length == 0) { Console.WriteLine("\nNo contribution for this event for the moment"); } else { foreach (var contribution in contributions) { Console.WriteLine(contribution.Name + " " + contribution.Type + " " + contribution.Quantity + " " + contribution.Person.Nickname); } } } catch (Exception) { goto default; } break; // GET ALL CONTRIBUTIONS OF A PERSON FOR ALL EVENTS case "NumPad2": try { Console.Write("Person's nickname: "); string nickname = Console.ReadLine(); var personToGetContributions = channel.GetPersonByNickname(nickname); if (personToGetContributions == null) { throw new Exception(); } var contributions = channel.GetAllContributionsFromPerson(personToGetContributions); if (contributions.Length == 0) { Console.WriteLine("\nThis person has no contribution for the moment"); } else { foreach (var contribution in contributions) { Console.WriteLine(contribution.Name + " " + contribution.Type + " " + contribution.Quantity + " " + contribution.Person.Nickname); } } } catch (Exception) { goto default; } break; // DELETE ALL CONTRIBUTIONS OF A PERSON FOR ALL OPEN EVENTS case "NumPad3": try { Console.Write("Person's nickname: "); string nickname = Console.ReadLine(); var personToDeleteContributions = channel.GetPersonByNickname(nickname); if (personToDeleteContributions == null) { throw new Exception(); } var contributions = channel.DeleteAllContributionsForAllOpenEventsFromPerson(personToDeleteContributions); if (contributions == false) { Console.WriteLine("\nThis person has no contribution for all his open events to delete"); } else { Console.WriteLine("\nContributions deleted"); } } catch (Exception) { goto default; } break; case "Escape": break; default: Console.WriteLine("\nEnter a valid value"); break; } } break; #endregion case "Escape": break; default: Console.WriteLine("\nEnter a valid value"); break; } } } catch (Exception ex) { Console.WriteLine("\nOOPS, an error occured:\n " + ex.Message); Console.WriteLine("Program will exit (Press any key)"); Console.ReadKey(true); } }
public ActionResult Edit(Contribution contribution) { if (ModelState.IsValid) { db.Entry(contribution).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.TypeID = new SelectList(db.ContributionTypes, "ID", "type", contribution.TypeID); ViewBag.E_ID = new SelectList(db.Events, "E_ID", "Name", contribution.E_ID); return View(contribution); }
void submit_text(RoutedEventArgs e) { bool is_design_idea = hide_expander; if (is_design_idea) { Contribution idea = new Contribution(); idea.date = DateTime.Now; idea.location_id = 0; idea.note = this.GetActiveTextBox().Text; idea.tags = "Design Idea"; database_manager.InsertDesignIdea(idea, this.comment_user_id); int collection_id = configurations.get_or_create_collection(this.comment_user_id, 1, DateTime.Now); Collection_Contribution_Mapping map = new Collection_Contribution_Mapping(); map.collection_id = collection_id; map.contribution_id = idea.id; map.date = DateTime.Now; database_manager.InsertCollectionContributionMapping(map); if (the_item.Content != null) ((design_ideas_listbox)the_item.Content).list_all_design_ideas(); //window_manager.load_design_ideas(); log.WriteInteractionLog(42, "Idea" + "; Text: " + this.GetActiveTextBox().Text + "; object_type: " + _object_type + "; object_id: " + _object_id.ToString(), ((TouchEventArgs)e).TouchDevice); window_manager.close_submit_design_idea_window((window_frame)this.parent, idea.note); //if (((design_ideas_listbox)the_item.Content).parent != null) // ((design_ideas_listbox)the_item.Content).parent.list_all_design_ideas(); } else { Feedback comment = new Feedback(); comment.date = DateTime.Now; comment.note = this.GetActiveTextBox().Text; comment.object_id = this._object_id; comment.object_type = this._object_type.ToString(); //if (comments_listbox._list.SelectedIndex == -1) // comment.parent_id = 0; //else //{ //int p_id = (int)((item_generic)comments_listbox._list.Items[comments_listbox._list.SelectedIndex]).Tag; if (is_reply) comment.parent_id = reply_id; else comment.parent_id = 0; //} comment.technical_info = ""; comment.type_id = 1; comment.user_id = this.comment_user_id; database_manager.InsertFeedback(comment); if (is_reply) log.WriteInteractionLog(42, "Comment; Reply id: " + reply_id + "; Text: " + this.GetActiveTextBox().Text + "; object_type: " + _object_type + "; object_id: " + _object_id.ToString(), ((TouchEventArgs)e).TouchDevice); else log.WriteInteractionLog(42, "Comment; Text: " + this.GetActiveTextBox().Text + "; object_type: " + _object_type + "; object_id: " + _object_id.ToString(), ((TouchEventArgs)e).TouchDevice); if (this.the_item.Content != null) { try { item_generic_v2 v2 = (item_generic_v2)this.the_item.Content; v2.number.Text = (Convert.ToInt32(v2.number.Text) + 1).ToString(); } catch (Exception) { } } this.list_all_comments(); if (this._object_type.ToString() == "nature_net.Contribution") window_manager.load_design_ideas_sync(); } //this.GetActiveTextBox().SelectAll(); cancel_comment_auth_clicked(null, null); GotoDefaultMode(); comment_textbox_default.Text = ""; comment_textbox_reply.Text = ""; CheckTextBoxText(); }
public void addTask(Task task, int share) { Contribution cont = new Contribution(task, this, share); if (!Tasks.Contains(cont)) { Tasks.Add(cont); } }
protected void Button1_Click(object sender, EventArgs e) { //withdraw all money using (FinanceManagerDataContext db = new FinanceManagerDataContext()) { MemberWithdrawal _memberWithdrawal = new MemberWithdrawal() { CreatedBy = HttpContext.Current.User.Identity.Name, DateCreated = DateTime.Now, IsDeleted = false, InvestmentID = Convert.ToInt32( InvestmentIDHiddenField.Value), Narration = "Withdrawal For Rollover", WithdrawalIssuedByUserName = HttpContext.Current.User.Identity.Name, WithdrawnBy = "System", WithdrawalAmount = Convert.ToDecimal( txtFriend.Text) }; //submit withdrawal changes db.MemberWithdrawals.InsertOnSubmit(_memberWithdrawal); //update the status of the current investment Investment _currentinvestment = db.Investments.FirstOrDefault(i => i.InvestmentID == Convert.ToInt32(InvestmentIDHiddenField.Value)); _currentinvestment.IsActive = false; //get company profile LoanWebApplication4.CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault(); //get compound type -- thus, annully, monthly, weekly etc int compoundType = cProfile.CompoundFrequency.Value; LoanDuration _loanDuration = db.LoanDurations.FirstOrDefault(l => l.LoanDurationId == _currentinvestment.DurationTypeId.Value);//Convert.ToInt32(cboLoanDurationType.SelectedValue)); if (_loanDuration == null) return; //calculate matured amount for the new investment double _maturedAmountForNewInvestment; DateTime _maturityDate = DateTime.Now; decimal period = _currentinvestment.Duration.Value * _loanDuration.NumberOfMonths.Value / 12; if (_currentinvestment.InterestTypeId.Value == 1) //compound { _maturedAmountForNewInvestment = Utils.calculateCompoundInterest(Convert.ToDouble(_currentinvestment.MaturedAmount.Value), Convert.ToDouble(_currentinvestment.InsterstRate.Value), period, Utils.GetCompoundType(compoundType)); } else //2 for simple interest { _maturedAmountForNewInvestment = Utils.calculateSimpleInterest(Convert.ToDouble(_currentinvestment.MaturedAmount.Value), Convert.ToDouble(_currentinvestment.InsterstRate.Value), period); } //create new investment Investment _newInvestment = new Investment() { IsActive = true, InvestmentTypeId = _currentinvestment.InvestmentTypeId, IsMatured = false, //ContributionFreqAmount = _currentinvestment.ContributionFreqAmount, //not calculating ContributionFreqAmount because after an investment is rolled over it becomes a fixed deposit Duration = _currentinvestment.Duration, DurationTypeId = _currentinvestment.DurationTypeId, GroupId = RadioButtonList1.SelectedIndex == 1 ? _currentinvestment.GroupId : null, InterestTypeId = _currentinvestment.InterestTypeId, InvestmentAmount = _currentinvestment.MaturedAmount, MaturedAmount = (decimal)_maturedAmountForNewInvestment, InvestmentCalculationStartDate = DateTime.Today, MaturityDate = _maturityDate, MemberID = RadioButtonList1.SelectedIndex == 0 ? _currentinvestment.MemberID : null, ParentInvestmentID = _currentinvestment.InvestmentID, InsterstRate = _currentinvestment.InsterstRate }; //calculate maturity date //variable to hold period for the calculation of MaturityDate calculation int tempPeriod; tempPeriod = Convert.ToInt32(_currentinvestment.Duration.Value) * _loanDuration.NumberOfMonths.Value; //start calculation from the LoanCalculationStartDate specified _newInvestment.MaturityDate = _newInvestment.InvestmentCalculationStartDate.Value.AddMonths(tempPeriod); //if the expected repayment end date falls on a weekend, move it to a working if (_newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Saturday) { _newInvestment.MaturityDate = _newInvestment.MaturityDate.Value.AddDays(2); } else if (_newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Sunday) { _newInvestment.MaturityDate = _newInvestment.MaturityDate.Value.AddDays(1); } db.Investments.InsertOnSubmit(_newInvestment); db.SubmitChanges(); //audit Utils.logAction("Insert", _newInvestment); Utils.logAction("Insert", _memberWithdrawal); //set current receipt number Parameter prm = db.Parameters.FirstOrDefault(); //increase receipt number by one prm.ReceiptNumber++; Contribution _newDeposit = new Contribution() { ContributionAmount = _currentinvestment.MaturedAmount, InvestmentId = _currentinvestment.InvestmentID, ContributionAmountInWords = Utils.ConvertMoneyToText(_currentinvestment.MaturedAmount.ToString()), ContributionBy = "System", Description = "Rollover from Investment: " + _currentinvestment.InvestmentID.ToString(), ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0'), RecievedBy = User.Identity.Name }; Response.Redirect(DropDownList1.SelectedIndex > 0 ? "MemberInvestments.aspx?mid=" + DropDownList1.SelectedValue : "GroupInvestments.aspx?gid=" + cboGroupName.SelectedValue); } }
/// <summary> /// Creates a contribution object given a string /// </summary> /// <param name="c">The commit object from Github</param> /// <param name="sha">The unique Sha from the Github commit object</param> /// <returns></returns> Contribution CreateContribution(Commit c, string sha) { var fact = new Contribution() { Sha = sha, Author = new Author() { Name = c.Author.Name, Email = c.Author.Email }, Date = c.Author.Date.UtcDateTime, Email = c.Author.Email, Message = c.Message, Spec = new Spec() { Name = RegexSpecName(c.Message) }, Organization = new Organization() { Name = TrackerData.GetNameAndOrganization(c.Author.Email)[1] }, Tracker = new Tracker() { Name = "Github" }, Url = c.Url }; return fact; }
public void updateContribution(Contribution c, int projectID) { using (var db = new PortfolioUnleashedContext()) { if (c.Title != null) db.Projects.Include("Contributions").FirstOrDefault(u => u.Id == projectID).Contributions.FirstOrDefault(cont => cont.UserId == c.UserId && cont.ProjectId == c.ProjectId).Title = c.Title; if (c.Description != null) db.Projects.Include("Contributions").FirstOrDefault(u => u.Id == projectID).Contributions.FirstOrDefault(cont => cont.UserId == c.UserId && cont.ProjectId == c.ProjectId).Description = c.Description; db.SaveChanges(); } }