|
Hi all
I am completely new to programming and C# but have been given a project which seems fairly difficult to me.
The project involves recreating the WW2 Enigma Machine cipher in a C# Windows Form. The machine has 3 rotors which contain all letters of the alphabet in a set order. These rotors turn one place on each use of the machine.
To allow for the rotors to turn, I have created a .txt file for each which has the 26 possible rotor settings. I will include a small example below...
EKMFLGDQVZNTOWYHXUSPAIBRCJ
KMFLGDQVZNTOWYHXUSPAIBRCJE
MFLGDQVZNTOWYHXUSPAIBRCJEK
FLGDQVZNTOWYHXUSPAIBRCJEKM
LGDQVZNTOWYHXUSPAIBRCJEKMF
The problem I am having is that I am unsure on how to read this file, only take the required line, and then be able to look at each character in order to carry out the cipher. i THINK I need to read the whole text into a string, grab another string from that using the first 26 characters (or until the new line), then separate the characters from there. Maybe....
If anyone could point me in the right direction I would hugely appreciate it. It is also very possible that I am looking at the situation in the wrong way, so any help would be great.
Thanks
Tetra1044
|
|
|
|
|
Depends on the exact organisation of your .txt file: if it has newlines between as rotor setting as you show in the example, then it's easy:
string[] rotorSettings = File.ReadAllLines(pathToFile);
If it doesn't, then you have options: you can read the whole file as a string and "chop out" the section you want with a substring:
string allSettings = File.ReadAllText(pathToFile);
string myRotor = allSettings.Substring(zerobasedIndexOfRotor * lengthOfSetting, lengthOfSetting);
Or if you are only interested in the characters in a rotor settign individually, then just access teh characters directly:
string allSettings = File.ReadAllText(pathToFile);
char first = allSettings[zerobasedIndexOfRotor * lengthOfSetting + 0];
char second = allSettings[zerobasedIndexOfRotor * lengthOfSetting + 1];
...
If there a lot of settings and you don't want to read them all, then create a Stream, and use Seek to locate the start of each setting in turn.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Thanks for the quick response Griff, I'll give that a go now
|
|
|
|
|
You're welcome!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Worked great, thanks again!
|
|
|
|
|
What an interesting assignment !
The pictures I've seen of the Engima machines that used rotors with alpha-numeric characters all show A~Z; I'm curious why your "sample" doesn't suggest that alpha-numeric order.
«I'm asked why doesn't C# implement feature X all the time. The answer's always the same: because no one ever designed, specified, implemented, tested, documented, shipped that feature. All six of those things are necessary to make a feature happen. They all cost huge amounts of time, effort and money.» Eric Lippert, Microsoft, 2009
modified 4-Feb-15 12:32pm.
|
|
|
|
|
The outside appearance of the rotors do show A-Z, but the wiring inside connects the letters to completely different letters.
So using a 5-letter example...
ABCDE would be shown on the outside, but the wires could be connecting...
DCAEB. Then on the next rotation, A = C, then A = A, A = E, etc.
So in the sample above I'm plotting the possible connections with A-Z. My thinking is that I will convert a user's keyboard input to a number 0-25, which can then be used to grab the correct ciphered letter from an array
|
|
|
|
|
I'm working on a web project and I need to do the following. I want to run different cmdlets on a VMM server (https://technet.microsoft.com/en-us/library/dn246490.aspx).
Right now when I need to run a cmdlet I open a runspace, connect to the VMM server using this cmdlet:
https://technet.microsoft.com/library/jj613273%28v=sc.20%29.aspx and then disconnect.
The problem is that disconnect doesn't work as expected and so I have memory leaks.
The solution is to use one connection to the server,using the previous cmdlet, and then perform all other actions via this connection (on new runspaces).
So I need to share the fact that I'm connected on each new runspace I open. I suppose I should use the RunspacePool class and maybe the InitialSessionState member but I'm not sure.
Thanks for your help!
ps: http://stackoverflow.com/questions/28254778/how-to-share-a-server-connection-between-different-powershell-runspaces-in-c-sha[^]
|
|
|
|
|
Does this have anything to do with C#?
|
|
|
|
|
Of course.Runspaces and code is running in C# using System.Management.Automation.
Thanks for replying!
|
|
|
|
|
Writing a class library, in which function return a string value based on window message received using the window handle.
Currently, not able to wait asynchronously to receive window message. Below is pseudo code which is being used.
namespace TestIntialization
{
public class Example : Form
{
string status = "";
public string init()
{
Example ex = new Example();
ex.intialise(this.Handle);
return status;
}
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x2000)
{
status = "SUCESS";
}
if (m.Msg == 0x2001)
{
status = "FAILURE";
}
base.WndProc(ref m);
}
}
}
Tried option like Thread.sleep,EventWaitHandle's WaitOne function but this function block the running thread. I am receiving expected window message in WndProc handler but value are reaching message handler only after exiting init function. So not able to inform calling application about success or failure status.
|
|
|
|
|
Assuming you're using .NET 4.0 or higher, something like this should work:
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
public static class MessageReceiver
{
public static Task<string> WaitForMessage(Control window)
{
if (window == null) throw new ArgumentNullException("window");
return new MessageListener(window).Status;
}
private sealed class MessageListener : NativeWindow
{
private const int WM_SUCCESS = 0x2000;
private const int WM_FAILURE = 0x2001;
private readonly TaskCompletionSource<string> _status = new TaskCompletionSource<string>();
public MessageListener(Control parent)
{
_parent.HandleCreated += OnHandleCreated;
_parent.HandleDestroyed += OnHandleDestroyed;
if (_parent.IsHandleCreated)
{
OnHandleCreated(_parent, EventArgs.Empty);
}
}
private void OnHandleCreated(object sender, EventArgs e)
{
AssignHandle(((IWin32Window)sender).Handle);
}
private void OnHandleDestroyed(object sender, EventArgs e)
{
ReleaseHandle();
}
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_SUCCESS:
{
_status.TrySetResult("SUCCESS");
base.WndProc(ref m);
ReleaseHandle();
break;
}
case WM_FAILURE:
{
_status.TrySetResult("FAILURE");
base.WndProc(ref m);
ReleaseHandle();
break;
}
default:
{
base.WndProc(ref m);
break;
}
}
}
public Task<string> Status
{
get { return _status.Task; }
}
}
}
With .NET 4.5, waiting for the message is as simple as:
private async Task Foo()
{
string status = await MessageReceiver.WaitForMessage(theForm);
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
HI,
Everybody,
I am new in C#, I want to know that what is structures and Enum in c#?What it's use?And what is difference between struct and Enum???
Thanks...
In Advance...
|
|
|
|
|
They are totally different things.
An enum is a list of named constants which are (generally, but not always they can be byte, sbyte, short, ushort, uint, long, or ulong instead) integer.
They are used to "group" related values such as the results you can get when you toss a coin: Heads and Tails
public enum CoinResult
{
Heads,
Tails,
} The system handles the values assigned to CoinResult.Heads and CoinResult.Tails - and you just use the names in your code:
CoinResult toss = FlipTheCoin(coin);
switch(toss)
{
default: throw new ArgumentException("Unknown CoinResult: " + toss);
case CoinResult.Heads:
Console.WriteLine("It came down heads up.");
break;
case CoinResult.Tails:
Console.WriteLine("It came down with the tails showing.");
break;
}
This makes your code a lot more readable:
int toss = FlipTheCoin(coin);
switch(toss)
{
default: throw new ArgumentException("Unknown coin flip state: " + toss);
case 1:
Console.WriteLine("It came down heads up.");
break;
case 2:
Console.WriteLine("It came down with the tails showing.");
break;
}
And enum doesn't have fields, properties, events, or methods; and cannot be used to derive a new type. See here: https://msdn.microsoft.com/en-us/library/sbbt4032.aspx[^]
A struct is different: it's a "slimline class". For the moment when you see struct you can mentally replace it with class - there are significant differences, but your tutor or book will cover these later. For reference, there is this: Using struct and class - what's that all about?[^] but I would recommend that you don't read it yet - it's a bit advanced and is likely to confuse you until you are a little further into your course. Read it later!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
In addition to studying the wise words that OriginalGriff posted in his reply to you, I would recommend you read this CodeProject article: "Enums and Structs in C#" [^]; it's an old article but a solid introduction.
This CodeProject article (recent) goes into some detail about how Enums are used in programming: [^].
A special feature of Enums is the use of the 'Flags attribute that allows creating "combinations" of attributes. If you ever want to express a combination like "Monday and Tuesday and Thursday" then an Enum with the Flags attribute is very useful. This CP article gives a good overview of Enums with Flags: [^].
While the 'Struct ValueType in .NET may have as its "ancestor" the very simple data-structure'Struct in the C language, in .NET it has many of the capabilities that classes also have: a Struct can include "constructors, constants, fields, methods, properties, indexers, operators, events, and nested types." And, a Struct can contain reference Types.
In practice, it is less common to see a Struct that includes other Types that are not ValueTypes/IntegralTypes, and it is usually considered better practice to go ahead and create a Class, rather than a Struct if you wish to use these other Types.
Like a Class, a Struct can inherit from an Interface(s), but it cannot inherit from a Class, and no other Type can inherit from a Struct.
The Microsoft docs on Using Structs are good, and have good examples" [^].
«I'm asked why doesn't C# implement feature X all the time. The answer's always the same: because no one ever designed, specified, implemented, tested, documented, shipped that feature. All six of those things are necessary to make a feature happen. They all cost huge amounts of time, effort and money.» Eric Lippert, Microsoft, 2009
|
|
|
|
|
In addition to what OriginalGriff said about enums is that I found them very powerful to enforce certain limitation onto yourself and others (developers, but also users).
It will reduce errors .
|
|
|
|
|
this is the code I got and it works unless you abbreviate days mon tue etc this is the string
string sPattern = "^(Mon|(T(ues|hurs))|Fri)(day|\\.)?$|Wed(\\.|nesday)?$|T((ue?)|(hu?r?))\\.?$";
how can I modify the string to just Monday Tuesday etc?
|
|
|
|
|
I do not know if I understand your question.
But for day of week (without abbreviates or weekend day) is suitable regex:
^(Mon|Tues|Wednes|Thurs|Fri)day$
|
|
|
|
|
Member 11354386 wrote: how can I modify the string to just Monday Tuesday etc?
Try
^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)$
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
|
You're welcome!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Hi y'all. I've noticed since switching to Windows 8 that a custom service that I wrote never really gets shut down because of the Windows 8 fast startup feature. I would like to still have my service do its shutdown processing even during a hybrid shutdown. So my question is: When Windows 8 does a hybrid shutdown, is there some new message I can receive in my service to do what I want? In other words, in my service I'm handling the SERVICE_CONTROL_PRESHUTDOWN message. Is there now a SERVICE_CONTROL_PRE_HYBRID_SHUTDOWN message? How do I detect or register to receive a hybrid shutdown message?
|
|
|
|
|
It's possible that what you're looking for is a notification of a power event.
MSDN states:
Quote: dwEventType [in]
If dwControl is SERVICE_CONTROL_POWEREVENT, this parameter can be one of the values specified in the wParam parameter of the WM_POWERBROADCAST message.
Perhaps when the system is going into hybrid shutdown, it sends this control code.
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
Thanks, that's a direction I could explore. Ill post
some results here soon.
|
|
|
|
|
Well, I tried using the SystemEvents.PowerModeChanged event, which is the managed analog to what you suggested. I received the Suspend and Resume events just fine but nothing for a power down (even a hybrid one). The mode enumeration is not terribly detailed. It offers Resume (aka wake), Suspend (aka sleep), and some other battery-related modes which are not pertinent to my problem. The return values from the PInvoke you suggested look much the same, so I did not try that.
Also note that I did my experimenting from a Windows Forms program. To do this from a service, MS says it's required to have a message pump in the service, which involves a hidden form and sounds kind of kludgey.
Instead I have this work around: I didn't mention that I also have a user tray app running that monitors the service. On a sleep the system doesn't exit the tray app. On a hybrid shutdown the system does. So in the form close event of tray app I use the CloseReason to find out if it's a non-user exit. If it is I send a custom message to the service to do it's shutdown processing. Sending a custom message is pretty easy:
ServiceController sc = new ServiceController("MyService");
sc.ExecuteCommand(MYSERVICE_QUASI_SHUTDOWN);
...then in the service, the custom command is handled in the OnCustomCommand event handler. MYSERVICE_QUASI_SHUTDOWN is some constant int you pick.
I've read that there's some valid range for it, so as not to step on the future, however I forget what that is just now.
|
|
|
|
|