[Code snippets] How to “refresh” a value in a C# Console Application

In this post I will be discussing how to refresh a value in C# Console applications.


While still in bed this morning,  I was skimming /r/csharp on Reddit and because it is so easy to just keep scrolling while on the phone, I happened to find a quite old subject. By old I mean six days with the latest reply being two days ago. That is old on the internet.

Anyway, the question was in essence if it is possible to refresh a value in a C# Console application. This got me intrigued, as I thus far have not worked too much with Console applications in this language, and did not know if it was possible. I read the answers, and because of the nature of /r/csharp, the preferred way to answer is not to spoon feed, but to give hints or link to places were one could get a push to figure out the answer oneself.

However, the original poster did not seem to get how this was to be done, so I kind of wanted to see if I could do it, because I like a challenge. Though it really was not a challenge, it was quite easy actually, it was kind of enjoyable, so I decided to play around a little with it.


As a programmer, generally the first thing you want to is to query ones favourite search engine, mine being Google (which I soon will write a blog post on how to properly use Google). The rule is, shorten your question into key terms and search away. So, I figured these were “refresh value console c#“, and sure enough, the first link was a StackedOverflow question that answered the question.

Since I did this after reading the answers on Reddit, I thought I would try to refresh a value in a Console application using the links provided by /u/TrikkyMakk and /u/wydok, both of which gave excellent answers. I will start of with the latter, as that was the shorter and slightly easier one, but also a little more restrictive.


/u/wydok’s answer was to use Console.Write() instead of Console.WriteLine(), because it does not automatically create a new line, but just keeps writing on the same line until it is told otherwise.

Because of how a C# Console application works, if it starts writing where other characters are, it simply writes over it – kind of like writing while having Insert on in for example Word. So, by starting the string inside the brackets with \r, the expression for Carriage Return, whatever is written in the Console will be overwritten by what is inside the string after \r. Here is an example using a Timer to automatically update the value.


// Declare an object called timer and the integer.
private static Timer timer;
private static int i = 0;
static void Main(string[] args)
{
// Set the timer to be a new Timer with an interval of 2 seconds.
timer = new Timer(2000);
// Everytime that interval has been reached, fire off this event.
timer.Elapsed += OnTimedEvent;
// The timer is now enabled and will start printing stuff.
timer.Enabled = true;
// Print the "first" value
Console.Write("{0}", i);
// This one waits for user input, as long as none is given, the progam will go on forever.
// (I.E. a key is not pressed)
Console.ReadKey();
// Will just flash by as the program will be closing.
Console.WriteLine("Terminating the application…");
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
// Increment the integer
i++;
// \r makes the console go back all the way on the row,
// and {0} prints out whatever the first value is on the other side of the comma (which in this case is the integer i).
Console.Write("\r{0}", i);
}

Note: If the new string is shorter than the old one, the new will only write over as much as it can, and leave the rest. For example, if the original string is “abcdefg” and the new is “\rABC” the final string will be “ABCdefg”.


 

While the above is cool and all, it might not be specifically what the original poster needs, so I also tried the answer that /u/TrikkyMakk gave, with great success. Since the answer was a little on the short side – being nothing but a link – I opened the link and followed the steps provided by Microsoft in said link, which included a very cool method using Console.SetCursorPosition(), which allows the programmer to specify where the Console should write next (as long as it is on the screen).

After doing that, I played around a little myself and decided to go for a Timer again, some Randoms and a list of all the letters in the alphabet. Because of how the Random object works, it is crucial only one Random object is used for all the random operations, otherwise, if two were to be used, both are highly likely to produce the same number, which is not really what is wanted.

What I got is a weird Console application that write random numbers in a 6 x 6 square.


// Declaring the integers used for positioning.
protected static int origingalRow;
protected static int originalColoumn;
protected static void WriteAt(string s, int x, int y)
{
// If an exception (error) is thrown insde the catch,
// the program will, in fact, not crash and whatever code inside catch will be run.
try
{
// Sets the position to write on and then writes there.
Console.SetCursorPosition(originalColoumn + x, origingalRow + y);
Console.Write(s);
}
catch (ArgumentOutOfRangeException e)
{
// Clear the Console and write the exception message.
Console.Clear();
Console.WriteLine(e.Message);
}
}
// For the fun of it, let's create a Timer.
protected static Timer timer;
static void Main(string[] args)
{
// Clear screen, then save the top and left coordinates,
// which should be top of the screen at the moment
Console.Clear();
originalColoumn = Console.CursorLeft;
origingalRow = Console.CursorTop;
// Instantiate timer with an interval of 0.2 seconds.
timer = new Timer(200);
// Everytime that interval's been reached, fire off this event.
timer.Elapsed += advancedTimer_Elapsed;
// Enable the timer to start printing stuff.
timer.Enabled = true;
// This one waits for user input, as long as none is given, the progam will go on forever.
// (I.E. a key is not pressed)
Console.ReadKey();
// Will just flash by as the program will be closing.
Console.WriteLine("Terminating the application…");
}
// Create a list of all the letters in the English alphabet
protected static List<string> englishAlphabet = new List<string>()
{
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k","l","m", "n", "o","p","q","r","s","t","u", "v", "x", "y", "z"
};
private static void advancedTimer_Elapsed(object sender, ElapsedEventArgs e)
{
// Instantiate a Random object. Only one, though!
Random random = new Random();
// A letter somewhere from the English alphabet.
string letter = englishAlphabet[random.Next(0, englishAlphabet.Count)];
// Get the coordinates
int x = random.Next(0, 5);
int y = random.Next(0, 5);
// Print the letter at x and y.
WriteAt(letter, x, y);
}


In conclusion, it is possible to refresh a value in a C# Console application. If a whole row is to be refreshed, and that is the last and only row to be altered, one can use Console.Write(“\rWrites over whatever else was here.”). If a more complex overwrite or refresh has to be done, one can use the Console.SetCursor()-method to specify where to write.

Happy coding!

 

[Code snippets] How to “refresh” a value in a C# Console Application

[How to] The story of how to embed Word documents in WordPress

In this post I will discuss and go through the steps of how to embed Word documents on WordPress using Word Online. It is written in a train of thought style, and gets pretty long winded, so if you do not like that, just skip to the conclusion.

Happy reading!


As usual this week, we have been doing tutorials in the module Media, Computers and Networks, and as I usually do, I upload those to my Portfolio. I do this, not because I have to, but because I want to.

In this tutorial, we worked with binary addition and things similar to that. When working in word, the easiest way to do that is using tables so the numbers will line up. With pen and paper, that is easy, but I am a computer type person, so I prefer using that.

Anyway.

When uploading documents to the portfolio, I generally provide a download link for the document and paste the actual content of it in the visual editor in WordPress, and that has worked just fine. Until today, when I posted the tables I mentioned IT WAS ALL OVER THE PLACE AND LOOKED REALLY WEIRD.

There had to be a better way!

As of this February, I have been hosting all of my course work on OneDrive, to make sure I always can reach them. This is beneficial in so many ways, especially now, since I have like 1.21 TB or storage there as well! The main reason, though, is because I now can go from my laptop to my tablet without a hassle!

Why am I telling you this, you may ask? The reason I am telling you this is I remembered seeing something about embedding in OneDrive a while ago. And that is exactly what I want to do! So I checked under Sharing in the editor using Word Online, and I found nothing.

Well, I did find something, but it was not what I was looking for. So I looked under Edit Document. Nothing. Print? No. I do not even know why I checked there, but I did, and I was disappointed. Then I checked under File > Share and there it was, and it was glorious!

Embed.

I was ecstatic! It is possible to embed Word documents in WordPress! I also tried right clicking in the OneDrive folder, and sure enough, there is an embed button there as well! Woo! When you click it, it gives you a screen that prompts you to click the Generate button, which generates HTML code for you.

Even though the code is not WordPress code it is just to copy it straight into the editor and WordPress converts it automatically for you! It is amazing!  Below is an example:

Here is how the code for the example looks in HTML:

https://gist.github.com/drklump/d6aec66d2db36a0e9586

And this is how it looks after WordPress converted it:

https://gist.github.com/drklump/9d4a920f1470a5dd3e6f

Also, it is possible to play around with the size of the window as well, but you have to make sure they still are the same ratio, otherwise it seems like it will not render. I do not know why, but that is the way it works. For me at least.


Conclusion

In this post I have told the story of how I stumbled upon how embedding a Word document in WordPress works. In short, it is done by first  saving the document to OneDrive, and while in OneDrive, Right Clicking it and then clicking embed. A window will show and there click Generate and Copy the code given by OneDrive. After that, it is just to paste the code into the editor in WordPress and it will do the rest for you!

Thank you for reading!

[How to] The story of how to embed Word documents in WordPress

[How to] Dual pages in Word and keybaord shortcuts

This will hopefully be a short blog, but I felt like I had to share this! [Naïvely written in the beginning of this blog. I suck at this.]

Note: I am using Microsoft Word 2013 in the 365 package on a Swedish Keyboard layout on a non-Mac laptop, so these may not work on other keyboard layouts. Usually, these commands are the same, but instead of using the button that says Ctrl, use the button that says Cmd, COMMAND or whatever they have on them (the one with the cinnamon roll-thingy).


The purpose of this post is to demonstrate a really cool feature of Microsoft Word 2013 (and possibly other versions of it, as well).

So, today I spent the majority of my day finishing up my first report in which I researched and wrote about FOSDIC – Film-Optical Sensing Device for Input to Computers. I will write another blog post about FOSDIC, because that is not that point of this blog, and when it is graded, I will make it available as well, because there is second to no information about it online. FOSDIC is not even mentioned on Wikipedia! The reason I am waiting with putting it online is I do not want the software the uni uses to see it as complete plagiarism, because it found an exact copy of it online. I do not know if that is how their system works, but I just want to be sure.

That was longer than necessary. Anyway, this cool feature I found is best shown by the image below:

If you look really closely, you can see that the reader is split into two and show two different parts of the same documents, where I can write in both. Obviously I cannot write in both at the same time, but I can easily swap between. I found this very useful when tying together the summary and ending.

So, how did I do this? I accidentally clicked Ctrl + Alt + S (at the same time, obviously, and without the “+”) when trying to figure out how to use the asdsad shortcut. Back in my day, it used to be Ctrl + Shift + S, but now Save As is moved to F12 instead. I mean, waht.  I cannot even bother to correct that “what” – I am that confused.

I am off track again. To split the view in Word 2013 and probably older versions as well (I do not know), either use the keyboard shortcut Ctrl + Alt + S or go to Ctrl+ View > Split.


I figure I should reveal some other shortcuts as I am already talking about keyboard shortcuts and whatnot. And they are not hidden, of course, but some may not have thought about it.

  • Ctrl + S should be rather obvious. I use it way to often. by that, I mean I sometimes use it while still inside a word. Not between words, inside of words. It is Save.
  • Ctrl + Shift + S (in older versions of Word) or F12 (at least in Word 2013) is for Save As.
  • Ctrl + Alt + S is as I have discussed for spliting the window.
  • Ctrl + O is O for open.
  • Ctrl + P has the same logic as above. What can it be? **
  • Ctrl + K is not as logical, as this is the shortcut for Add Link.
  • Ctrl + F is a godsend. F is for find, and it is lovely.
  • Ctrl + D lets you choose font in Word, and in most web browsers it is Add Bookmark
  • [Windows logo] + D minimises every window and displays the desktop.
  • [Windows logo] + E opens the file explorer to This PC.
  • Ctrl + Shift + Escape does what the old Ctrl + Alt + Delete used to do back in my day. It opens the task manager which is mainly used for when you cannot wait two seconds to close the program (this is not good, though, because many programs save stuff when they are closing).
  • Ctrl + Space usually opens up the intellisense menu/autofill menu in some (many?) IDEs (programs for writing other programs***).
  • [Windows Logo] + Enter apparently opens/closes Narrator in Windows 8.1. probably older versions as well.

There are loads of others as well, of course, so if you actually want to speed your computer usage up a bit, you can read more here. Thus far everyone seem to believe you are some kind of computer wizard when only using shortcuts instead of touching the mouse.

Ehrm, I mean. I am a wizard.

Thanks for reading!

 

 

 

** Print… P is for print.
*** Well…

[How to] Dual pages in Word and keybaord shortcuts