Iterative solution to train problem to practice class and object basics

Ive done a little bit of programming in the past, mostly just dabbling. After a long time of not touching an IDE, I am getting back into it. I just threw this quick project together to make sure I remember how to use classes and objects before I start playing with bigger projects.

I would love a quick critique to make sure there arent any glaring poor practices that could develop into bad habbits in the future.

I know the standard way to solve this problem is just time = distance/(velA+velB), but what would the point of using objects be if i didnt have the objects do something and change their status in someway?

what do you think, looks good?

/*  The goal for this practice program is to solve the common math word problem below using classes and objects. I feel that using iterations rather than the basic math formula to solve, although clearly less efficient, would be more true to thinking in terms of objects.  Train A, traveling X miles per hour (mph), leaves Westford heading toward Eastford, 260 miles away. At the same time Train B, traveling Y mph, leaves Eastford heading toward Westford. When do the two trains meet? How far from each city do they meet?  */  #include "pch.h" #include <iostream> using namespace std;  class Train { public:     Train(int, int);     int getLocation();     void update(); private:     int location, velocity; };  Train::Train(int loc, int vel) //to initialize the train object and set its location and velocity {     location = loc;     velocity = vel; }  int Train::getLocation() // returns the location of the train object {     return location; }  void Train::update() // updates the train object for one iteration {     location += velocity; }  int main() {     int velA, velB, distance; //to take the values from the user input     int time;   // to keep track of the number of iterations                 // time is declared here so it can be used outside of the for loop       //input     cout << "Enter velocity of the train from Westford:\n";     cin >> velA;     cout << "\n\nEnter velocity of the train from Eastford:\n";     cin >> velB;     cout << "\n\nEnter the distance between Westford and Eastford:\n";     cin >> distance;      //initialize each train     Train trainA(0, velA);     Train trainB(distance, 0 - velB);   //location of trainB is distance because the distance between an x coordinate at 0 and another x coordinate is equal to the second x coordinate                                         //the velocity of trainB is the negative of velB because it is traveling in the opposite direction of trainA      //run the sim     for (time = 0; trainA.getLocation() < trainB.getLocation(); time++)     {         trainA.update();         trainB.update();     }      //output     cout << "\n\nThe Trains pass eachother after " << time << " hours."         << "\nAt that time, the Westford train is " << trainA.getLocation() << " miles from Westford\n"         << "and the Eastford train is " << distance - trainB.getLocation() << " miles from Eastford.\n\n";      return 0; } 

Referencing the instantiated class object within a method belonging to the same class

I have an object called InSiteMessage in C#. I would like to include a method within this class, which converts the object to a JSON string and returns it.

I can do this via the below, but it feels wrong? Is it accepted design to do this sort of self-referencing, or is there a better way to achieve this?

Here is my class (note the method ConvertMessageToJson)

public class InSiteMessage {     public string packageName;     public Guid packageId;     public string packageSourceServer;     public DateTime createdDateTime;     public MessageState state { get; set; }     public string stateReadable { get { return state.ToString(); } }     public List<IProcessable> listActivities { get; set; }     public List<Location> targetLocations { get; set; }     public List<Location.ForwardLocation> forwardLocations { get; set; }      public InSiteMessage(string messageName, List<IProcessable> activities)     {         packageName = messageName;         packageId = Guid.NewGuid();         createdDateTime = DateTime.Now;         listActivities = activities;         targetLocations = new List<Location>();         forwardLocations = new List<Location.ForwardLocation>();          //Assign sequence Ids          int i = 0;         activities.ForEach(x => x.sequenceId = i++);     }      public void SetSourceServer()     {         packageSourceServer = Environment.MachineName;     }      public void SetMessageState(MessageState currentState)     {         state = currentState;     }      public string ConvertMessageToJson(InSiteMessage message)     {         var settings = new JsonSerializerSettings { ContractResolver = BaseFirstContractResolver.Instance };         return JsonConvert.SerializeObject(message, Formatting.Indented, settings);     }  } 

As you can see, the method takes an InSiteMessage into itself in order to convert to JSON, so calling it sems a little… weird:


Is it safe to enable – Trust Access to the VBA object model – Microsoft Office

I am trying to run a VBS script which calls a macro and won’t run unless I click “Trust Access to the VBA object model” in Microsoft Office Trust Center. I forget where I read it but I thought I read this was extremely unsafe. This project is for work and I wanted to know if this is something that is considered safe.

C++ writing object data to file

I’m trying to write a program that stores usernames and passwords. So I have created a Record class. Each record has an id, title, username, and password field. I want to write each record to a text file.

However, I am having some issues. When I compile I get the following errors.

'Record::getTitle': non-standard syntax; use '&' to create a pointer to member 'Record::getUsername': non-standard syntax; use '&' to create a pointer to member 'Record::getPassword': non-standard syntax; use '&' to create a pointer to member 

The problem:

writeToFile(firstRecord.getTitle, firstRecord.getUsername, firstRecord.getPassword); 

The getTitle(and others) return a string. So I am not sure why this isn’t working. Any suggestions would be appreciated.

Complete code (so far) below..

#include <iostream> #include <string> #include <fstream> #include <map> #include <functional> using namespace std;  string GetInput(); void MainMenu(); void Title(); void AddRecord(); void writeToFile(string title, string username, string password);  class Record {  private:      string id;     string title;     string username;     string password;     static int numberOfRecords;  public:      void setTitle(string title) {         this->title = title;     }     string getTitle() {         return title;     }      void setUsername(string username) {         this->username = username;     }     string getUsername() {         return username;     }      void setPassword(string password) {         this->password = password;     }     string getPassword() {         return password;     }      static int GetNumberOfRecords() {         return numberOfRecords;     } };  struct MenuAction {      string description;     function<void()> action; };  static const map <string, MenuAction> actionTable{      { "1",{ "Add entry", []() { AddRecord(); } } },     { "2",{ "Edit entry", []() { cout << "Edit entry" << "\n";  } } },     { "q",{ "Quit", []() { cout << "Quit" << "\n";  } } } };  int main() {      Title();     MainMenu();      return 0; }  void Title() {      cout << "======================================\n"             "|              Database              |\n"             "======================================\n\n"; }  void MainMenu() {      for (auto const& x : actionTable) {         cout << x.first << ". " << (x.second).description << "\n";     }      string input;      while (actionTable.count(input) == 0) {         input = GetInput();     }; }  void AddRecord() {      cout << "============= Add Record ============" << endl << endl;      string id;     string title;     string username;     string password;      cout << "Title: ";     getline(cin, title);     cout << "Username: ";     getline(cin, username);     cout << "Password: ";     getline(cin, password);      Record firstRecord;     firstRecord.setTitle(title);     firstRecord.setUsername(username);     firstRecord.setPassword(password);      writeToFile(firstRecord.getTitle, firstRecord.getUsername, firstRecord.getPassword); }  string GetInput() {      string s = "";      cout << ">> ";     getline(cin, s);      return s; }  void writeToFile(string title, string username, string password) {      ofstream outFile;"database.txt", ios_base::app);     outFile << title << "\t" << username << "\t" << password << "\n";      cout << "============= Record Added To Database ============" << endl; } 

Feel free to comment or nag other portions of my code 🙂

Object Oriented Design: Repositories and Inheritance

I have an OO design concern: let’s say in my model I have a base class – eg. class Account {} – and two subclasses that extend it – eg. class LocalAccount extends Account {} and class SocialAccount extends Account {}.

These Account entities are persisted, and I could retrieve them (or do more operations on them) through a typical Repository. Let’s say I have the following interface:


interface AccountRepository {     getAll(): Array<Account> ; } 

And I have some use-cases where I need to work with Accounts where I basically would inject the AccountRepository, eg.

class FooUseCase {      private AccountRepository accountRepository;      constructor(AccountRepository accountRepository) {         this.accountRepository = accountRepository;     }      public execute(): void {         // Use case logic where I would call accountRepository.getAll()     }  } 

And at this point is where I am actually struggling. After some analysis, I thought about having specific AccountRepository implementations:


class LocalAccountRepository implements AccountRepository {      public getAll(): Array<LocalAccount> { /* implementation */ }  } 


class SocialAccountRepository implements AccountRepository {      public getAll(): Array<SocialAccount> { /* implementation */ }  } 

This would be alright, as far as a use-case would just need to work with LocalAccount or SocialAccount entities. But, what would happen if I would just needed to work with Account entities?

I feel I could implement an AccountRepository, generic enough that could just return a list of Accounts, eg.


class AccountRepositoryImpl implements AccountRepository {      public getAll(): Array<Account> { /* implementation */ }  } 

but I feel that at the public getAll(): Array<Account> I would somehow have to add some kind of switch/if-else statement to be able to create each type of Account object:


public getAll(): Array<Account> {     // Database access, query, etc.      // results iteration      let account: Account;      if (result.type === AccountType.Local) {         account = new LocalAccount(/* params */);     } else if (result.type === AccountType.Social) {         account = new SocialAccount(/* params */);     }      accounts.add(account);      // iteration end      return accounts; } 

Which clearly violates some design principles (every time a new Account is added would have to extend the if-else, etc.).

Any design improvement suggestions to my issues?

Insecure Direct Object Reference – Change email from client end

I am testing a website that has “Forgot my password” functionality. If user clicks that, his email address will be displayed as a hyperlink. If that is clicked, an email to reset password will be triggered to that Address. As an end user, I can change the hyperlink using Chrome developer tools to point to some other valid email address and trigger password reset to that user. Should I flag this issue? What are the implications this issue might have?

How to get date from `DateTime` object returned by stored procedure

I have a datetime object that I am extracting from a datatable returned by a stored procedure called in my Asp.Net app.

DataTable tableInfo = _dtMgr.GetInfoByID(uxGridView.SelectedDataKey.Value.ToString()); tableInfo.Rows[0]["dateOfEvent"]; 

It returns the following: {3/19/2019 10:11:0000 AM}. I am simply trying to get the date ‘3/19/2019’ and have tried the following. No matter what I do, it still returns {3/19/2019 10:11:0000 AM}. Any suggestions?

What I’ve tried:

var dt1 = Convert.ToDateTime(tableInfo.Rows[0]["dateOfEvent"]).Date; //dt1 returns {3/19/2019 10:11:0000 AM} var dt2 = //same dt1.Tostring('MM/dd/yyyy'); // too many characters in literal error 

Note: These are all solutions I have seen in similar questions about extracting the date from a datetime object in C#. None of them seem to work.

SqlException: Invalid object name ‘Usuari’

Estoy intentando mostrar una vista con la lista de usuarios pero cuando voy a la vista me devuelve este error: Error aplicación

Tengo la cadena de conexion a la DB en appsettings.json

"ConnectionStrings": { "DefaultConnection": "Data Source=XXXX\XXXX;Initial Catalog=GUS;User ID=XXXXX;Password=XXXXX;Trusted_Connection=True;MultipleActiveResultSets=true" } 

En mi startup.cs tengo esto:

public void ConfigureServices(IServiceCollection services)     {          services.AddDbContext<GusContext>(options =>             options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 

En mi controlador, esto:

 public class UsuarisController : Controller {     private readonly GusContext _context;      public UsuarisController(GusContext context)     {         _context = context;     }      // GET: Usuaris     public async Task<IActionResult> Index()     {         return View(await _context.Usuaris.ToListAsync());     } 

El modelo Usuari.cs es este:

namespace Gus.Models { public class Usuaris {     [Key]     public int idUsuari { get; set; }     public string samlString { get; set; }     public string mail { get; set; }     public string nom { get; set; }     public ICollection<UsuarisCentres> UsuarisCentres { get; set; }     public ICollection<Rols> Rols { get; set; } } } 

El GusContext este:

using Gus.Models; using Microsoft.EntityFrameworkCore;  namespace Gus.Data { public class GusContext : DbContext {     public GusContext(DbContextOptions<GusContext> options) : base(options)     {      }      public DbSet<lkCentres> Centres { get; set; }     public DbSet<lkInstitucions> Institucions { get; set; }     public DbSet<Rols> Rols { get; set; }     public DbSet<Usuaris> Usuaris { get; set; }     public DbSet<UsuarisCentres> UsuarisCentres { get; set; }       protected override void OnModelCreating(ModelBuilder modelBuilder)     {         modelBuilder.Entity<lkCentres>().ToTable("Centre");         modelBuilder.Entity<lkInstitucions>().ToTable("Institucio");         modelBuilder.Entity<Rols>().ToTable("Rol");         modelBuilder.Entity<Usuaris>().ToTable("Usuari");         modelBuilder.Entity<UsuarisCentres>().ToTable("UsuariCentre");     } } } 

Y finalmente la vista recibe un IEnumerable de Gus.Models.Usuaris y un foreach me debería de printa una tabla.

A ver si me podéis echar una mano, soy bastante novatillo y ando un poco perdido.


What is the name of the pattern where the framework owns your event/state object and you don’t keep a pointer to it?

There’s a pattern sometime used that I’d like to know the name for. It’s when you have a domain-specific state object that keeps track of progress through some kind of multi-step process which is run by some framework or engine – but you yourself never keep a copy of or pointer to that state. In fact, you just create it, pass it to your framework, and then every once in awhile you get called back on it (or with it as a param), you modify it and return to the framework, and so on, but you never hold that object.

In C++ it can look funky when you get called back and decide your chain-of-processes is through and you just delete this and return, which normally is pretty wierd but in this case it’s just business.

In C++ it can look really funky because sometimes you do a “naked new” where you don’t even store your object into any kind of local/collection/whatever. Instead, just the act of creating your object and passing into it a parameter that represents the framework causes the object to “register” itself with the framework, passing ownership, and it looks like the new object is just lost, and so you get code that looks like this:

new FooProcess(&frameworkContext, param1, param2); while (true) { ... _event loop here_ ... } 

gRPC uses this pattern as seen in the official tutorial for asynchronous processing – search for occurrences of new CallData. And you can also look for delete this in there.

So, what is this pattern called?

(Bonus question: Once you’ve named the thing for me – thank you! – discuss for extra credit whether it’s a good idea or not – especially w.r.t. initially debugging your code and then with maintaining it when it fails under load or other resource pressure… The reason I’m asking this question is because I’d like to read what other people think of it but can’t figure out how to search for it.)