I'm using windows 10 (maybe this is the problem:-) )
I have a simple code that reads text in Hebrew from console them print it's HEX\DEC value
but he give me 00 all the time
on the console window I can see the Hebrew letters
any reason why?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Net;
using System.Net.Sockets;
using System.Timers;
using System.IO;
namespace HebTest
{
class Program
{
static public void Main(string[] args)
{
Console.WriteLine("Write your message here - ");
string StringMessage = Console.ReadLine();
Console.WriteLine("print string - " + StringMessage);
///message in HEX
byte [] ByteMessage = Encoding.Default.GetBytes(StringMessage);
string HexMessage = BitConverter.ToString(ByteMessage);
Console.WriteLine("MSG in HEX - " + HexMessage);
Console.Write(
Encoding.Default.GetString(ByteMessage)
);
Console.WriteLine();
foreach (byte p in ByteMessage)
{
Console.Write((char)p + " - " + p );
Console.WriteLine("");
}
}
for example I enter this text
"test אבגד"
and this is what I got :
Write your message here -
test אבגד ---> this I wrote on the console
print string - test
MSG in HEX - 74-65-73-74-20-00-00-00-00
test
t - 116
e - 101
s - 115
t - 116
- 32
- 0
- 0
- 0
- 0
what am I missing?
Thanks ,
You're using Encoding.Default to convert the string into binary. That's almost always a bad idea - it means the same code may work on some machines and not on others. It's pretty much only useful when you want to read/write a text file on that machine, and you're sure that the system default encoding is the right one to use for any machine that runs it. That's rare.
In particular, you're trying to talk to an external device - which means you need to use the encoding it expects. You should find that out, and use the appropriate encoding. For example, if the device expects UTF-8, use:
// Local variable names changed to be more idiomatic C#
string text = Console.ReadLine();
byte[] bytes = Encoding.UTF8.GetBytes(text);
As you've now indicated that the device expects Windows-1255, that's code page 1255, so you get the encoding like this:
Encoding.GetEncoding(1255)
For clarify, I'd probably use a separate variable for that:
string text = Console.ReadLine();
Encoding encoding = Encoding.GetEncoding(1255);
byte[] bytes = encoding.GetBytes(text);
Found the problem (after #Daisy Shipton let me think )
the code is OK
need to go to
control Panel - region - administrative - system locale -
REMOVE V on Beta : use Unicode UTF-8 for worldwide language support
hope it will help someone someday
Related
I am new to programming and taking my first course, programming fundamentals and on our current homework assignment I have a problem I cannot get.
The problem is- "A bag of cookies holds 40 cookies. The calorie information on the bag claims that there are 10 servings in the bag and that a serving equals 300 calories. Create an application that lets the user enter the number of cookies he or she actually ate and then reports the number of calories consumed."
My form:
The error i get when I run without debugging:
//below is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Calorie_Counter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int cookies = int.Parse(textBox1.Text);
int calories = (cookies * 75);
textBox2.Text = calories.ToString();
}
}
}
You encounter this problem when using the int.Parse() method. This method simply converts whatever you passed to it as a string to int. So, something like "33" will be converted, but what if you entered something that is clearly not an integer such as "x" or even an empty string?
So, this will be converted to a value of 33 in int type no problem.
int parseResultGood = int.Parse("33");
But this will fail and throw an exception, because, obviously "x" cannot be converted into an integer.
int parseResultBad = int.Parse("x");
Luckily though, C# provides you another method to handle this better, namely, int.TryPrase() method. As the name suggests it tries to parse the value, and converts it into an int only if it is possible and send it back to you in the out parameter while it will return true. If the conversion failed, say, because you passed a non-integer value as a string, it will return false, and the value of the out parameter will be zero. So based on the return value of true/false you can know if the conversion was successful or not, and it won't thrown an exception.
int tryParseResult = 0;
if (int.TryParse("X", out tryParseResult))
{
// Use the converted value
}
else
{
// Display an error message or something similar
}
However, I suggest you learn to debug your program. If you did, you'd have been able to figure out the problem for yourself. The article that was linked to in comments is a great one, please follow it. Good luck!
1) Create new console application, with Visual Studio that you will call consolehw.
2)You will create a text file with that will have a list of at least 10 names of people. This file should be called names.txt and it should be placed inside the Debug folder of your consolehw application
3) You will create a simple program to access this file using streams. You should first add your name the end of this file in a new line. After that, you will present in the console (Command Line if running in Windows or Terminal if running in Mac) all the names of the file and at the end of it, in a new line, a text that would say “There are X new participants in the seminar ” where X will be the number of lines (number of names) you read from the names.txt file after adding your name to it.
Notice that the first 10 names were already included in names.txt file. Your name should be included via the program and the final message that shows the X with the value of 11 new participants in the seminar.
Ive tried to append, and create arrays but I'm stumped on how to add the lines and display the number of names or lines in a message (string).
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Consolehw
{
class Program
{
static void Main(string[] args)
{
string p = #"names.txt";
using (StreamWriter sr = File.AppendText(p))
{ sr.WriteLine(Environment.NewLine + "- Peter Lancer - "); sr.Close();
Console.WriteLine(File.ReadAllText(p)); }
String msg = "There are X new participants";
Console.Write(msg);
Console.ReadKey();
}
}
}
results were mentioned in summary as a guideline.
Suppose that the maximum IP can contain the maximum number of 999 in each "dot" bracket,i.e. 999.999.999.999 is the largest available. I've checked the regex ([0-9]+.){3}[0-9] in the calculator. So, why the program throws the run-time error "parsing "?([0-9]+.){3}[0-9]" - Quantifier {x,y} following nothing."?
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace RegExCs
{
class Program
{
static void Main(string[] args)
{
string rawData;
Regex filter = new Regex(#"?<ip>([0-9]+\.){3}[0-9]"); //run-time error
rawData=File.ReadAllText("Query list");
MatchCollection theMatches = filter.Matches(rawData);
foreach (Match theMatch in theMatches)
{
Console.WriteLine("ip: {0}\n",theMatch.Groups["ip"]);
}
Console.ReadKey();
}
}
}
Official help page wasn't so helpful for me.
"Query list" file content:
Reply from 212.77.100.101 www.wp.pl time: 21:37
Reply from 111.41.130.55 www.dupa.pl time: 05:33
Reply from 230.77.100.101 www.whatanannoyingbug.com time: 04:12
Reply from 65.77.100.101 www.foooo.org time: 12:55
Reply from 200.77.100.101 www.example.com time: 07:56
You need to surround your entire regex with parentheses, change ?<ip>([0-9]+\.){3}[0-9] to the following:
(?<ip>([0-9]+\.){3}[0-9])
This is necessary because the ?<name> syntax for creating a named group only works immediately following an opening parentheses, otherwise ? means "make the previous element optional". Since there is no previous element before the ?, you are getting an error.
I would use this to ensure it's a REAL (0-255) IP address:
(([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))\.){3}([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))
I am trying to get a MAC TripleDES equivalent of the C# MACTripleDES class.
I have tried following mcrypt(), but that is just encoding in TripleDES. I need to get an equivalent MACTripleDES string as the one that is generated in C# to authenticate a message.
I have also looked at PHP's hash_hmac() function but it does not give the option of generating a MAC with TripleDES
I'm not sure since Microsoft didn't bother to say what standard their class conforms to, but I suspect that this NIST document is what the Microsoft class is computing, only using triple DES in place of DES.
I guess you will have to write your own method using the primitives in mcrypt.
EDIT 1:
Inspired by the bounty, I have these two examples showing equivalent result in PHP and C#.
First, C#:
using System;
using System.Text;
using System.Security.Cryptography;
namespace TDESMacExample
{
class MainClass
{
public static void Main (string[] args)
{
var keyString = "012345678901234567890123";
var keyBytes = Encoding.ASCII.GetBytes(keyString);
var mac = new MACTripleDES(keyBytes);
var data = "please authenticate me example number one oh one point seven niner";
Console.WriteLine(data.Length);
var macResult = mac.ComputeHash(Encoding.ASCII.GetBytes(data));
Console.WriteLine(BitConverter.ToString(macResult));
// B1-29-14-74-EA-E2-74-2D
}
}
}
Next, PHP:
<?php
$data = 'please authenticate me example number one oh one point seven niner';
$key = '012345678901234567890123'; // Key must be 24 bytes long
$iv = '\x00\x00\x00\x00\x00\x00\x00\x00'; // All zero IV is required
$cipher = mcrypt_cbc(MCRYPT_3DES, $key, $data, MCRYPT_ENCRYPT, $iv);
$mac_result = substr($cipher, -8); // Last 8 bytes of the cipher are the MAC
echo "mac result : " . bin2hex($mac_result);
echo "<br>";
?>
The MAC is simply the last eight bytes of the CBC encrypted data. If the key, IV, and the padding method matches, you should be able to just use those bytes.
For more details about MAC definition, see Appendix F of FIPS-81, DES Modes of Operation.
I googled and found the solution at MSDN.
// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);
file.Close();
How to extend the lines to complex content which including some natural C# code lines.
eg. I want to write the information below to my test.cs file.
Why?
I am parsing a XML schema with C# Console Application. And i want to generate the Console Result to a .cs file during the compiler time.
using System;
using System.Collections.Generic;
using System.Text;
namespace CommonDef
{
public class CCODEData
{
public int iCodeId;
public string sCode;
public CODEDType cType;
public int iOccures;
}
[Description("CodeType for XML schema.")]
public enum CODEDType
{
cString = 1,
cInt = 2,
cBoolean = 3,
}
thank you.
If your source code is hardcoded as in your sample, you could use a C# literal string:
string lines =
#"using System;
using System.Collections.Generic;
using System.Text;
namespace CommonDef
..."
Anyway in such cases it is a better idea (more readable and maintainable) to have the whole text contents into a text file as an embedded resource in your assembly, then read it using GetManifestResourceStream.
(I'm assuming you're trying to build up the result programmatically - if you genuinely have hard-coded data, you could use Konamiman's approach; I agree that using an embedded resource file would be better than a huge verbatim string literal.)
In your case I would suggest not trying to build up the whole file into a single string. Instead, use WriteLine repeatedly:
using (TextWriter writer = File.CreateText("foo.cs"))
{
foreach (string usingDirective in usingDirectives)
{
writer.WriteLine("using {0};", usingDirective);
}
writer.WriteLine();
writer.WriteLine("namespace {0}", targetNamespace);
// etc
}
You may wish to write a helper type to allow simple indentation etc.
If these suggestions don't help, please give more details of your situation.
I know an answer has already been accepted but why not use an XSLT applied to the XML instead? this would mean that you could easily generate c#, vb.net, .net without having to recompile the app.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FileHandling
{
class Class1
{
static void Main()
{
Console.WriteLine("Enter data");
ConsoleKeyInfo k;
//Console.WriteLine(k.KeyChar + ", " + k.Key + ", " + k.Modifiers );
string str="";
char ch;
while (true)
{
k = Console.ReadKey();
if ((k.Modifiers == ConsoleModifiers.Control) && (k.KeyChar == 23))
{
Console.WriteLine("\b");
break;
}
if (k.Key == ConsoleKey.Enter)
{
Console.WriteLine("");
str += "\n";
}
ch = Convert.ToChar(k.KeyChar);
str += ch.ToString();
}
Console.WriteLine(str);
Console.Read();
}
}
}