public bool Filename_9600() { string portName; int baudRate = 9600; string fileName = portName = "PortNameEqualToFileName.txt"; System.IO.FileStream testFile = System.IO.File.Open(fileName, System.IO.FileMode.Create); System.Text.ASCIIEncoding asciiEncd = new System.Text.ASCIIEncoding(); string testStr = "Hello World"; bool retValue = false; testFile.Write(asciiEncd.GetBytes(testStr), 0, asciiEncd.GetByteCount(testStr)); testFile.Close(); try { retValue = VerifyCtor(portName, baudRate, typeof(ArgumentException), ThrowAt.Open); } catch (Exception) { throw; } finally { System.IO.File.Delete(fileName); } return(retValue); }
public void Filename_9600_Space_8() { string portName; int baudRate = 9600; int parity = (int)Parity.Space; int dataBits = 8; string fileName = portName = "PortNameEqualToFileName.txt"; System.IO.FileStream testFile = System.IO.File.Open(fileName, System.IO.FileMode.Create); System.Text.ASCIIEncoding asciiEncd = new System.Text.ASCIIEncoding(); string testStr = "Hello World"; testFile.Write(asciiEncd.GetBytes(testStr), 0, asciiEncd.GetByteCount(testStr)); testFile.Close(); try { VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentException), ThrowAt.Open); } catch (Exception) { throw; } finally { System.IO.File.Delete(fileName); } }
private bool PortName_FileName() { string fileName = "PortNameEqualToFileName.txt"; System.IO.FileStream testFile = System.IO.File.Open(fileName, System.IO.FileMode.Create); System.Text.ASCIIEncoding asciiEncd = new System.Text.ASCIIEncoding(); string testStr = "Hello World"; testFile.Write(asciiEncd.GetBytes(testStr), 0, asciiEncd.GetByteCount(testStr)); testFile.Close(); Console.WriteLine("Verifying setting PortName={0}", fileName); if (!VerifyException(fileName, ThrowAt.Open, typeof(System.ArgumentException), typeof(System.InvalidOperationException))) { Console.WriteLine("Err_004!!! Verifying setting PortName to a file name FAILED"); return(false); } Console.WriteLine("Verifying setting PortName={0}", Environment.CurrentDirectory + fileName); if (!VerifyException(Environment.CurrentDirectory + fileName, ThrowAt.Open, typeof(System.ArgumentException), typeof(System.InvalidOperationException))) { Console.WriteLine("Err_009!!! Verifying setting PortName to a file name FAILED"); return(false); } System.IO.File.Delete(fileName); return(true); }
private void DoPosTest(string source, int expectedValue) { ASCIIEncoding ascii; int actualValue; ascii = new ASCIIEncoding(); actualValue = ascii.GetByteCount(source); Assert.Equal(expectedValue, actualValue); }
/// <summary> /// Schickt den Spielernamen zzum Server um ein Spiel zu starten /// </summary> /// <param name="name">Spielername</param> /// <param name="sock">Zu benutzender Socket</param> private void SendPlayerName(string name, ref Socket sock) { System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); byte[] message = new byte[enc.GetByteCount(name) + 1]; enc.GetBytes(name, 0, name.Length, message, 1); message[0] = enc.GetBytes("n")[0]; NonBlockingConsole.WriteLine("Sending " + enc.GetString(message) + " to " + sock.RemoteEndPoint.ToString() + " from " + sock.LocalEndPoint.ToString()); sock.Send(message); }
private void DoPosTest(char[] chars, int startIndex, int count, int expectedValue) { ASCIIEncoding ascii; int actualValue; ascii = new ASCIIEncoding(); actualValue = ascii.GetByteCount(chars, startIndex, count); Assert.Equal(expectedValue, actualValue); }
public void NegTest1() { ASCIIEncoding ascii; string source = null; ascii = new ASCIIEncoding(); Assert.Throws<ArgumentNullException>(() => { ascii.GetByteCount(source); }); }
public void SendEvent(string str) { if (HasClients) { int len = encoder.GetByteCount(str); byte[] bytes = new byte[len + 1]; encoder.GetBytes(str, 0, str.Length, bytes, 0); bytes[len] = 0; SendBytes(bytes); } lock (history) { history.Enqueue(str); while (history.Count > 100) { history.Dequeue(); } } }
public void NegTest1() { ASCIIEncoding ascii; char[] chars = null; ascii = new ASCIIEncoding(); Assert.Throws<ArgumentNullException>(() => { ascii.GetByteCount(chars, 0, 0); }); }
/// <summary> /// Helper function to generate a temporary file with the given content and extension. /// </summary> /// <param name="text">File content.</param> /// <param name="ext">File extension.</param> /// <returns></returns> private String internalCreateTestFile(String text, String ext) { String tempName = internalMakeTempFileName(ext); System.IO.FileStream fstrm = new System.IO.FileStream(tempName, System.IO.FileMode.Create, System.IO.FileAccess.Write); System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); int n = encoding.GetByteCount(text); byte[] buf = new byte[n]; encoding.GetBytes(text, 0, text.Length, buf, 0); fstrm.Write(buf, 0, buf.Length); fstrm.Close(); return(tempName); }
static public int GetByteCount__A_Char(IntPtr l) { try { System.Text.ASCIIEncoding self = (System.Text.ASCIIEncoding)checkSelf(l); System.Char[] a1; checkArray(l, 2, out a1); var ret = self.GetByteCount(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
public void PosTest2() { ASCIIEncoding ascii; byte[] bytes; int byteIndex, byteCount; char[] chars; int charIndex; string source; ascii = new ASCIIEncoding(); source = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH); bytes = new byte[ascii.GetByteCount(source)]; ascii.GetBytes(source, 0, source.Length, bytes, 0); byteIndex = TestLibrary.Generator.GetInt32(-55) % bytes.Length; byteCount = TestLibrary.Generator.GetInt32(-55) % (bytes.Length - byteIndex) + 1; chars = new char[byteCount + TestLibrary.Generator.GetInt32(-55) % c_MAX_STRING_LENGTH]; charIndex = TestLibrary.Generator.GetInt32(-55) % (chars.Length - byteCount + 1); DoPosTest(ascii, bytes, byteIndex, byteCount, chars, charIndex); }
public void PortName_FileName() { string fileName = "PortNameEqualToFileName.txt"; System.IO.FileStream testFile = System.IO.File.Open(fileName, System.IO.FileMode.Create); System.Text.ASCIIEncoding asciiEncd = new System.Text.ASCIIEncoding(); string testStr = "Hello World"; testFile.Write(asciiEncd.GetBytes(testStr), 0, asciiEncd.GetByteCount(testStr)); testFile.Close(); Debug.WriteLine("Verifying setting PortName={0}", fileName); VerifyException(fileName, ThrowAt.Open, typeof(ArgumentException), typeof(InvalidOperationException)); Debug.WriteLine("Verifying setting PortName={0}", Environment.CurrentDirectory + fileName); VerifyException(Environment.CurrentDirectory + fileName, ThrowAt.Open, typeof(ArgumentException), typeof(InvalidOperationException)); System.IO.File.Delete(fileName); }
public void PosTest2() { ASCIIEncoding ascii; char[] chars; int charIndex, count; byte[] bytes; int byteIndex; ascii = new ASCIIEncoding(); InitializeCharacterArray(out chars); charIndex = _generator.GetInt32(-55) % chars.Length; count = _generator.GetInt32(-55) % (chars.Length - charIndex) + 1; int minLength = ascii.GetByteCount(chars, charIndex, count); int length = minLength + _generator.GetInt32(-55) % (Int16.MaxValue - minLength); bytes = new byte[length]; for (int i = 0; i < bytes.Length; ++i) { bytes[i] = 0; } byteIndex = _generator.GetInt32(-55) % (bytes.Length - minLength + 1); DoPosTest(ascii, chars, charIndex, count, bytes, byteIndex); }
public void PosTest2() { ASCIIEncoding ascii; string source; int charIndex, count; byte[] bytes; int byteIndex; ascii = new ASCIIEncoding(); source = _generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH); charIndex = _generator.GetInt32(-55) % source.Length; count = _generator.GetInt32(-55) % (source.Length - charIndex) + 1; int minLength = ascii.GetByteCount(source.Substring(charIndex, count)); int length = minLength + _generator.GetInt32(-55) % (Int16.MaxValue - minLength); bytes = new byte[length]; for (int i = 0; i < bytes.Length; ++i) { bytes[i] = 0; } byteIndex = _generator.GetInt32(-55) % (bytes.Length - minLength + 1); DoPosTest(ascii, source, charIndex, count, bytes, byteIndex); }
public static int Main(string[] args) { /** * Get the arguments */ if( args.Length < 2 ) { Console.Error.WriteLine("usage: SNodeExample.exe [tcp|udp] port remota_ta0 remote_ta1 ..."); return 0; } /** * Make the edge listener: */ EdgeListener el = null; int port = Int32.Parse( args[1] ); if( args[0].ToLower() == "tcp" ) { el = new TcpEdgeListener(port); } else if( args[0].ToLower() == "udp" ) { el = new UdpEdgeListener(port); } /** * Create a random address for our node. * Some other application might want to select the address * a particular way, or reuse a previously selected random * address. If the addresses are not random (or the output * of secure hashes) the network might not behave correctly. */ RandomNumberGenerator rng = new RNGCryptoServiceProvider(); AHAddress tmp_add = new AHAddress(rng); Console.WriteLine("Address: {0}", tmp_add); /** * Make the node that lives in a particular using Brunet.Messaging; * namespace (or realm) called "testspace" */ Node tmp_node = new StructuredNode(tmp_add, "testspace"); ReqrepManager rrman = tmp_node.Rrm; ReqrepExample irh = new ReqrepExample(); tmp_node.GetTypeSource(PType.Protocol.Chat).Subscribe(irh, tmp_node); /** * Add the EdgeListener */ tmp_node.AddEdgeListener( el ); /** * Tell the node who it can connect to: */ for(int i = 2; i < args.Length; i++) { tmp_node.RemoteTAs.Add( TransportAddressFactory.CreateInstance( args[i] ) ); } /** * Now we connect */ tmp_node.Connect(); Console.WriteLine("Connected"); /** * In a real application, we would create some IAHPacketHandler * objects and do: * tmp_node.Subscribe( ) * finally, we could send packets using tmp_node.Send( ) or * tmp_node.SendTo( ) */ string msg = ""; System.Text.Encoding coder = new System.Text.ASCIIEncoding(); while( true ) { Console.Write("To: "); msg = Console.ReadLine(); if ( msg == "q" ) { break; } Address dest = AddressParser.Parse(msg); while( msg != "." ) { msg = Console.ReadLine(); int length = coder.GetByteCount(msg); byte[] payload = new byte[length]; coder.GetBytes(msg, 0, msg.Length, payload, 0); ISender sender = new AHSender(tmp_node, dest); rrman.SendRequest(sender, ReqrepManager.ReqrepType.Request, new CopyList(PType.Protocol.Chat, MemBlock.Reference(payload)), irh , null); } } return 1; }
public static int Main(string[] args) { /** * Get the arguments */ if (args.Length < 2) { Console.Error.WriteLine("usage: SNodeExample.exe [tcp|udp] port remota_ta0 remote_ta1 ..."); return(0); } /** * Make the edge listener: */ EdgeListener el = null; int port = Int32.Parse(args[1]); if (args[0].ToLower() == "tcp") { el = new TcpEdgeListener(port); } else if (args[0].ToLower() == "udp") { el = new UdpEdgeListener(port); } /** * Create a random address for our node. * Some other application might want to select the address * a particular way, or reuse a previously selected random * address. If the addresses are not random (or the output * of secure hashes) the network might not behave correctly. */ RandomNumberGenerator rng = new RNGCryptoServiceProvider(); AHAddress tmp_add = new AHAddress(rng); Console.WriteLine("Address: {0}", tmp_add); /** * Make the node that lives in a particular * using Brunet.Messaging; * namespace (or realm) called "testspace" */ Node tmp_node = new StructuredNode(tmp_add, "testspace"); ReqrepManager rrman = tmp_node.Rrm; ReqrepExample irh = new ReqrepExample(); tmp_node.GetTypeSource(PType.Protocol.Chat).Subscribe(irh, tmp_node); /** * Add the EdgeListener */ tmp_node.AddEdgeListener(el); /** * Tell the node who it can connect to: */ for (int i = 2; i < args.Length; i++) { tmp_node.RemoteTAs.Add(TransportAddressFactory.CreateInstance(args[i])); } /** * Now we connect */ tmp_node.Connect(); Console.WriteLine("Connected"); /** * In a real application, we would create some IAHPacketHandler * objects and do: * tmp_node.Subscribe( ) * finally, we could send packets using tmp_node.Send( ) or * tmp_node.SendTo( ) */ string msg = ""; System.Text.Encoding coder = new System.Text.ASCIIEncoding(); while (true) { Console.Write("To: "); msg = Console.ReadLine(); if (msg == "q") { break; } Address dest = AddressParser.Parse(msg); while (msg != ".") { msg = Console.ReadLine(); int length = coder.GetByteCount(msg); byte[] payload = new byte[length]; coder.GetBytes(msg, 0, msg.Length, payload, 0); ISender sender = new AHSender(tmp_node, dest); rrman.SendRequest(sender, ReqrepManager.ReqrepType.Request, new CopyList(PType.Protocol.Chat, MemBlock.Reference(payload)), irh, null); } } return(1); }
public static bool checksumVerify(string str) { bool ret = false; // the $ and * should NOT be included in computation, see http://joe.mehaffey.com/mag-errata.htm try { int posAst = str.IndexOf("*"); if (posAst != -1 && posAst <= str.Length - 3) { string csStr = str.Substring(posAst + 1, 2); ASCIIEncoding enc = new ASCIIEncoding(); uint l = (uint)enc.GetByteCount(str); byte[] s = enc.GetBytes(str); byte[] ast = enc.GetBytes("*"); int sum = 0; int len = s.GetLength(0); for (int i = 1; i < len - 3; i++) { if (s[i] == ast[0]) { break; } sum ^= s[i]; } sum = sum & 0xFF; ret = string.Format("{0:X2}", sum).Equals(csStr); } } catch { ret = false; } return ret; }
static void Main(string[] args) { //log.Debug( "Starting the Brunet Echo Tester" ); String config_file = args[0]; NetworkConfiguration network_configuration = NetworkConfiguration.Deserialize(config_file); int port_selection = Convert.ToInt32(args[1]); //There will be 10 different ports available for use: 0, 1, 2.. //for example, node 0 on a machine will use port_selection # 0, node 1 on a machine will use port_selection # 1 ///There will be multiple BruNet nodes on the same machine. The following is a list of possible ports used int list_size = 150; int [] port_list = new int[list_size]; for(int i = 0; i < list_size; i++){ port_list[i] = 25000 + i; } ///The line below is used when there is only one node per machine //int local_host_index = network_configuration.GetLocalHostIndex(); int desired_port = port_list[port_selection]; int local_host_index = network_configuration.GetLocalHostIndex(desired_port); NodeConfiguration this_node_configuration = (NodeConfiguration)network_configuration.Nodes[local_host_index]; TransportAddressConfiguration local_ta_configuration = (TransportAddressConfiguration)this_node_configuration.TransportAddresses[0]; short port = local_ta_configuration.Port; SHA1 sha = new SHA1CryptoServiceProvider(); String local_ta = local_ta_configuration.GetTransportAddressURI(); //We take the local transport address plus the port number to be hashed to obtain a random AHAddress byte[] hashedbytes = sha.ComputeHash(Encoding.UTF8.GetBytes(local_ta + port)); //inforce type 0 hashedbytes[Address.MemSize - 1] &= 0xFE; AHAddress _local_ahaddress = new AHAddress(hashedbytes); Node this_node = new StructuredNode( _local_ahaddress ); ///Node this_node = new HybridNode( new AHAddress( new BigInteger( 2*(local_host_index+1) ) ) ); String file_string = "./data/brunetadd" + Convert.ToString(desired_port) + ".log"; StreamWriter sw = new StreamWriter(file_string, false); sw.WriteLine( "local_address " + this_node.Address.ToBigInteger().ToString() + " " + Dns.GetHostName() + ":" + port); sw.Close(); if ( local_ta_configuration.Protocol == "tcp" ) { this_node.AddEdgeListener( new TcpEdgeListener(port) ); } else if( local_ta_configuration.Protocol == "udp" ) { this_node.AddEdgeListener( new UdpEdgeListener(port) ); } int remote_node_index = local_host_index-1; int num_remote_ta = 20; //20 nodes on the list to try to bootstrap to if (local_host_index!=0) { NodeConfiguration remote_node_configuration = (NodeConfiguration)network_configuration.Nodes[0]; TransportAddressConfiguration remote_ta_configuration = (TransportAddressConfiguration)remote_node_configuration.TransportAddresses[0]; String remote_ta = remote_ta_configuration.GetTransportAddressURI(); this_node.RemoteTAs.Add( TransportAddressFactory.CreateInstance( remote_ta ) ); } while ( (remote_node_index>=0) && (num_remote_ta>=0) ) { NodeConfiguration remote_node_configuration = (NodeConfiguration)network_configuration.Nodes[remote_node_index]; TransportAddressConfiguration remote_ta_configuration = (TransportAddressConfiguration)remote_node_configuration.TransportAddresses[0]; String remote_ta = remote_ta_configuration.GetTransportAddressURI(); this_node.RemoteTAs.Add( TransportAddressFactory.CreateInstance( remote_ta ) ); System.Console.WriteLine("Adding {0}", remote_ta); remote_node_index--; num_remote_ta--; } /* NodeConfiguration remote_node_configuration = (NodeConfiguration)network_configuration.Nodes[remote_node_index]; TransportAddressConfiguration remote_ta_configuration = (TransportAddressConfiguration)remote_node_configuration.TransportAddresses[0]; String remote_ta = remote_ta_configuration.GetTransportAddressURI(); this_node.RemoteTAs.Add( TransportAddressFactory.CreateInstance( remote_ta ) );*/ EchoTester echo_printer = new EchoTester(); this_node.GetTypeSource(PType.Protocol.Echo).Subscribe(echo_printer, this_node); this_node.Connect(); //Send a "hello message" to a random neighbor ASCIIEncoding ascii = new ASCIIEncoding(); //Make the target addresses AHAddress target = new AHAddress( new BigInteger( 2*(remote_node_index+1) ) ); string hello_msg = "hello, brunet"; int byteCount = ascii.GetByteCount(hello_msg); byte[] bytes = new byte[byteCount + 1]; ascii.GetBytes(hello_msg, 0, hello_msg.Length, bytes, 1); // update the payload // This is a request, so the first byte is greater than zero bytes[0] = (byte) 1; ICopyable p = new CopyList(PType.Protocol.AH, new AHHeader(0, 30, this_node.Address, target, AHHeader.Options.Greedy), PType.Protocol.Echo, MemBlock.Reference(bytes)); ///RDP Experiment: sending the echo packet periodically /* int seq = 0; while(true){ int start_time = System.DateTime.Now.Millisecond; this_node.Send(p); Console.WriteLine("Seq = {0}, Start Time = {1}", seq, start_time); System.Threading.Thread.Sleep(10000); seq++; }*/ ///The following is a while-loop for the local node to Brunet-ping all other nodes in the network System.Threading.Thread.Sleep(60000); ///IMPORTANT: change this parameter so we wait longer for larger network Random uid_generator = new Random( DateTime.Now.Millisecond + local_ta.GetHashCode() + port); bytes = new byte[5]; int target_index = 0, num_pings = 10, wait_time = 10000; //the wait_time is in ms double ping_time; PingWrapper pw = new PingWrapper(); while( target_index < network_configuration.Nodes.Count ){ if(target_index != local_host_index){///we do not ping the local machine NodeConfiguration target_node_configuration = (NodeConfiguration)network_configuration.Nodes[target_index]; TransportAddressConfiguration target_ta_configuration = (TransportAddressConfiguration)target_node_configuration.TransportAddresses[0]; short target_port = target_ta_configuration.Port; double ping1 = pw.Ping(target_ta_configuration.Address, 10000); double ping2 = pw.Ping(target_ta_configuration.Address, 10000); if(ping1 >= 0 || ping2 >= 0){ //we gather the data only when the node is ping-able sha = new SHA1CryptoServiceProvider(); String target_ta = target_ta_configuration.GetTransportAddressURI(); //We take the transport address plus the port number to be hashed to obtain a random AHAddress hashedbytes = sha.ComputeHash(Encoding.UTF8.GetBytes(target_ta + target_port)); //inforce type 0 hashedbytes[Address.MemSize - 1] &= 0xFE; AHAddress _target_ahaddress = new AHAddress(hashedbytes); for(int i = 0; i < num_pings; i++){ //ping and Brunet-ping the target node for a number of times int uid = uid_generator.Next(); //this is the unique id of the packet // update the payload // This is a request, so the first byte is greater than zero bytes[0] = (byte) 1; NumberSerializer.WriteInt(uid, bytes, 1); p = new CopyList(PType.Protocol.AH, new AHHeader(0, 30, this_node.Address, _target_ahaddress, AHHeader.Options.Greedy), PType.Protocol.Echo, MemBlock.Reference(bytes)); this_node.Send(p); ping_time = pw.Ping(target_ta_configuration.Address, wait_time); //wait wait_time number of ms System.Console.WriteLine("Ping time: {0}",ping_time); System.Threading.Thread.Sleep(wait_time); }//end of for-loop } }//end of if-loop target_index++; }//end of while-loop }
public static byte[] CByteASCII(string sData) { byte[] nuller = null; try { System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); byte[] byter = new byte[encoding.GetByteCount(sData)]; encoding.GetBytes(sData, 0, sData.Length, byter, 0); return byter; } catch { } return nuller; }
public void NegTest7() { ASCIIEncoding ascii; char[] chars; int charIndex, count; byte[] bytes; int byteIndex; ascii = new ASCIIEncoding(); InitializeCharacterArray(out chars); charIndex = _generator.GetInt32(-55) % chars.Length; count = _generator.GetInt32(-55) % (chars.Length - charIndex) + 1; int minLength = ascii.GetByteCount(chars, charIndex, count); bytes = new byte[minLength]; byteIndex = bytes.Length + _generator.GetInt32(-55) % (int.MaxValue - bytes.Length); DoNegAOORTest(ascii, chars, charIndex, count, bytes, byteIndex); }
/// <summary> /// Connects to the Remote Server and Updates the Player Info on it /// </summary> /// <param name="Server_address">Address of the Remote Server</param> /// <param name="Port_Num">Port Number on the Remote Server</param> /// <returns>True if update was successful, false otherwise</returns> private bool UpdateInfoOnServer(string Server_address, int Port_Num) { NetworkStream stream; //Stream to write and read data to ASCIIEncoding encoder = new ASCIIEncoding(); TcpClient client = new TcpClient(); IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3550); try { Console.Write("Connecting to server..."); client.Connect(serverEndPoint); Console.WriteLine("Connected!"); Console.Write("Sending data to server..."); //Write the GamerTag to the server stream = client.GetStream(); stream.Write(encoder.GetBytes(ToString()), 0, encoder.GetByteCount(ToString())); stream.Flush(); Console.WriteLine("Data sent!"); Console.Write("Reading return data..."); byte[] msg = new byte[4096]; int read = stream.Read(msg, 0, 4096); string message = ""; if (read > 0) { Console.WriteLine("Data returned!"); message = encoder.GetString(msg, 0, read); } else { Console.WriteLine("ERROR: No Data returned!"); return false; } } catch { Console.WriteLine("ERROR: Could not connect to server!"); return false; } return true; }
public EncoderParameter(Encoder encoder, string value) { this.encoder = encoder; ASCIIEncoding ascii = new ASCIIEncoding(); int asciiByteCount = ascii.GetByteCount(value); byte[] bytes = new byte[asciiByteCount]; ascii.GetBytes(value, 0, value.Length, bytes, 0); this.valuesCount = bytes.Length; this.type = EncoderParameterValueType.ValueTypeAscii; this.valuePtr = Marshal.AllocHGlobal(valuesCount); Marshal.Copy(bytes, 0, this.valuePtr, valuesCount); }
public void NegTest8() { ASCIIEncoding ascii; string source; int charIndex, count; byte[] bytes; int byteIndex; ascii = new ASCIIEncoding(); source = _generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH); charIndex = _generator.GetInt32(-55) % source.Length; count = _generator.GetInt32(-55) % (source.Length - charIndex) + 1; int minLength = ascii.GetByteCount(source.Substring(charIndex, count)); bytes = new byte[_generator.GetInt32(-55) % minLength]; byteIndex = 0; Assert.Throws<ArgumentException>(() => { ascii.GetBytes(source, charIndex, count, bytes, byteIndex); }); }
public static string checksum(string str) { // the $ and * should NOT be included in computation, see http://joe.mehaffey.com/mag-errata.htm ASCIIEncoding enc = new ASCIIEncoding(); uint l = (uint)enc.GetByteCount(str); byte[] s = enc.GetBytes(str); int sum = 0; int len = s.GetLength(0); for (int i = 1; i < len; i++) { sum ^= s[i]; } sum = sum & 0xFF; return string.Format("*{0:X2}\r\n", sum); }
/// <summary> /// Handles communication with the clients /// </summary> /// <param name="client"></param> private void HandleClientComm(object client) { String gamerID = ""; String sentString = ""; ASCIIEncoding encoder = new ASCIIEncoding(); TcpClient tcpClient = (TcpClient)client; NetworkStream clientStream = tcpClient.GetStream(); byte[] message = new byte[4096]; int bytesRead; bytesRead = 0; try { //blocks until a client sends a message bytesRead = clientStream.Read(message, 0, 4096); } catch { } //message has successfully been received sentString = encoder.GetString(message, 0, bytesRead); string[] tokens = sentString.Split(":".ToCharArray()); if (tokens.Length > 1)//We're getting an update string, so update { Console.WriteLine("Player Update data for " + tokens[1] + " recieved."); PlayerInfo info = new PlayerInfo(sentString); UpdatePlayerInfo(info); gamerID = info.PlayerName; } else { gamerID = sentString; } //If we have an ID, write the data back if (gamerID != "") { Console.WriteLine("GamerTag = " + gamerID); PlayerInfo info = GetPlayerInfo(gamerID); byte[] infoBytes = encoder.GetBytes(info.ToString()); clientStream.Write(infoBytes, 0, encoder.GetByteCount(info.ToString())); clientStream.Flush(); } tcpClient.Close(); }
private void DoNegAOORTest(char[] chars, int startIndex, int count) { ASCIIEncoding ascii = new ASCIIEncoding(); Assert.Throws<ArgumentOutOfRangeException>(() => { ascii.GetByteCount(chars, startIndex, count); }); }
public void NegTest8() { ASCIIEncoding ascii; char[] chars; int charIndex, count; byte[] bytes; int byteIndex; ascii = new ASCIIEncoding(); InitializeCharacterArray(out chars); charIndex = _generator.GetInt32(-55) % chars.Length; count = _generator.GetInt32(-55) % (chars.Length - charIndex) + 1; int minLength = ascii.GetByteCount(chars, charIndex, count); bytes = new byte[_generator.GetInt32(-55) % minLength]; byteIndex = 0; Assert.Throws<ArgumentException>(() => { ascii.GetBytes(chars, charIndex, count, bytes, byteIndex); }); }
private IntPtr GetNativeAnsiString(string str) { ASCIIEncoding strEncoder = new ASCIIEncoding(); int size = strEncoder.GetByteCount(str); IntPtr pStr = Memory.Zalloc(size + 1); byte[] buffer = strEncoder.GetBytes(str); Marshal.Copy(buffer, 0, pStr, size); return pStr; }
/// <summary> /// Retrieves the PlayerInfo from the given server /// </summary> /// <param name="PlayerName">PlayerName of the info to retriver</param> /// <param name="Server_Address">Address of the remoter server</param> /// <param name="Port_Num">Port on the remote server</param> /// <returns>True if the retrieval was successful, False otherwise</returns> public bool GetPlayerInfoFromServer(string PlayerName, string Server_Address, int Port_Num) { NetworkStream stream; //Stream to write and read data to ASCIIEncoding encoder = new ASCIIEncoding(); TcpClient client = new TcpClient(); IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(Server_Address), Port_Num); try { Console.Write("Connecting to server..."); client.Connect(serverEndPoint); Console.WriteLine("Connected!"); Console.Write("Sending data to server..."); //Write the GamerTag to the server String tag = "thenewzerov"; stream = client.GetStream(); stream.Write(encoder.GetBytes(tag), 0, encoder.GetByteCount(tag)); stream.Flush(); Console.WriteLine("Data sent!"); Console.Write("Reading return data..."); byte[] msg = new byte[4096]; int read = stream.Read(msg, 0, 4096); string message = ""; if (read > 0) { Console.WriteLine("Data returned!"); message = encoder.GetString(msg, 0, read); } else { Console.WriteLine("ERROR: No Data returned!"); return false; } CreateFromString(message); Console.WriteLine(ToString()); return true; } catch { Console.WriteLine("ERROR: Could not connect to server!"); return false; } }
protected virtual void writeHeader(int numChannels, double samplingRate, Task recordingTask) { DateTime dt = DateTime.Now; //Get current time (local to computer) double[] scalingCoeffs = recordingTask.AIChannels[0].DeviceScalingCoefficients; //Write header info: #chs, sampling rate, gain, date/time outStream.Write(BitConverter.GetBytes(Convert.ToInt16(-VERSION)), 0, 2); //Int: negative of file version (negative will prevent this from being confused with older versions, where this would be a positive numChannels field outStream.Write(BitConverter.GetBytes(Convert.ToInt16(numChannels)), 0, 2); //Int: Num channels outStream.Write(BitConverter.GetBytes(Convert.ToDouble(samplingRate)), 0, 8); //Int: Sampling rate outStream.Write(BitConverter.GetBytes(Convert.ToInt16(numSamplesPerWaveform)), 0, 2); //Int: Num samples per waveform outStream.Write(BitConverter.GetBytes(Convert.ToInt16(10.0 / recordingTask.AIChannels.All.RangeHigh)), 0, 2); //Double: Gain outStream.Write(BitConverter.GetBytes(Properties.Settings.Default.ADCPollingPeriodSec), 0, 8); // DAC polling period outStream.Write(BitConverter.GetBytes(Convert.ToInt16(dt.Year)), 0, 2); //Int: Year outStream.Write(BitConverter.GetBytes(Convert.ToInt16(dt.Month)), 0, 2); //Int: Month outStream.Write(BitConverter.GetBytes(Convert.ToInt16(dt.Day)), 0, 2); //Int: Day outStream.Write(BitConverter.GetBytes(Convert.ToInt16(dt.Hour)), 0, 2); //Int: Hour outStream.Write(BitConverter.GetBytes(Convert.ToInt16(dt.Minute)), 0, 2); //Int: Minute outStream.Write(BitConverter.GetBytes(Convert.ToInt16(dt.Second)), 0, 2); //Int: Second outStream.Write(BitConverter.GetBytes(Convert.ToInt16(dt.Millisecond)), 0, 2); //Int: Millisecond // Is the user recording unit information? outStream.Write(BitConverter.GetBytes(recordingUnits), 0, 1); //Int: Millisecond //Now we list the fields that each spike will have ASCIIEncoding encoder = new ASCIIEncoding(); const string DELIMITER = "|"; const string ChannelField = "channel"; outStream.Write(encoder.GetBytes(ChannelField), 0, encoder.GetByteCount(ChannelField)); outStream.Write(encoder.GetBytes(DELIMITER), 0, encoder.GetByteCount(DELIMITER)); outStream.Write(BitConverter.GetBytes(Convert.ToInt32(16)), 0, 4); //Num bits for this field outStream.Write(BitConverter.GetBytes('I'), 0, 1); //type: i for int, f for float const string TimeField = "time"; outStream.Write(encoder.GetBytes(TimeField), 0, encoder.GetByteCount(TimeField)); outStream.Write(encoder.GetBytes(DELIMITER), 0, encoder.GetByteCount(DELIMITER)); outStream.Write(BitConverter.GetBytes(Convert.ToInt32(32)), 0, 4); //Num bits for this field outStream.Write(BitConverter.GetBytes('I'), 0, 1); //type: i for int, f for float const string UnitField = "unit"; outStream.Write(encoder.GetBytes(UnitField), 0, encoder.GetByteCount(UnitField)); outStream.Write(encoder.GetBytes(DELIMITER), 0, encoder.GetByteCount(DELIMITER)); outStream.Write(BitConverter.GetBytes(Convert.ToInt32(16)), 0, 4); //Num bits for this field outStream.Write(BitConverter.GetBytes('I'), 0, 1); //type: i for int, f for float const string ThresholdField = "threshold"; outStream.Write(encoder.GetBytes(ThresholdField), 0, encoder.GetByteCount(ThresholdField)); outStream.Write(encoder.GetBytes(DELIMITER), 0, encoder.GetByteCount(DELIMITER)); outStream.Write(BitConverter.GetBytes(Convert.ToInt32(64)), 0, 4); //Num bits for this field outStream.Write(BitConverter.GetBytes('F'), 0, 1); //type: i for int, f for float outStream.Write(encoder.GetBytes(DELIMITER), 0, encoder.GetByteCount(DELIMITER)); //Terminal delimiter means we're done defining fields //Everything else is assumed to be the waveform samples }
/// <summary>Initializes the MPI environment.</summary> /// <param name="args"> /// Arguments passed to the <c>Main</c> function in your program. MPI /// may use some of these arguments for its initialization, and will remove /// them from this argument before returning. /// </param> /// <param name="threading"> /// The level of threading support requested of the MPI implementation. The /// implementation will attempt to provide this level of threading support. /// However, the actual level of threading support provided will be published /// via the <see cref="MPI.Environment.Threading"/> property. /// </param> /// <remarks> /// This routine must be invoked before using any other MPI facilities. /// Be sure to call <c>Dispose()</c> to finalize the MPI environment before exiting! /// </remarks> /// <example>This simple program initializes MPI and writes out the rank of each processor: /// <code> /// using MPI; /// /// public class Hello /// { /// static void Main(string[] args) /// { /// using (MPI.Environment env = new MPI.Environment(ref args)) /// { /// System.Console.WriteLine("Hello, from process number " /// + MPI.Communicator.world.Rank.ToString() + " of " /// + MPI.Communicator.world.Size.ToString()); /// } /// } /// } /// </code> /// </example> public Environment(ref string[] args, Threading threading) { if (!Initialized) { int requiredThreadLevel = 0; int providedThreadLevel; switch (threading) { case Threading.Single: requiredThreadLevel = Unsafe.MPI_THREAD_SINGLE; break; case Threading.Funneled: requiredThreadLevel = Unsafe.MPI_THREAD_FUNNELED; break; case Threading.Serialized: requiredThreadLevel = Unsafe.MPI_THREAD_SERIALIZED; break; case Threading.Multiple: requiredThreadLevel = Unsafe.MPI_THREAD_MULTIPLE; break; } if (args == null) { unsafe { int argc = 0; byte** argv = null; Unsafe.MPI_Init_thread(ref argc, ref argv, requiredThreadLevel, out providedThreadLevel); } } else { ASCIIEncoding ascii = new ASCIIEncoding(); unsafe { // Copy args into C-style argc/argv int my_argc = args.Length; byte** my_argv = stackalloc byte*[my_argc]; for (int argidx = 0; argidx < my_argc; ++argidx) { // Copy argument into a byte array (C-style characters) char[] arg = args[argidx].ToCharArray(); fixed (char* argp = arg) { int length = ascii.GetByteCount(arg); byte* c_arg = stackalloc byte[length]; if (length > 0) { ascii.GetBytes(argp, arg.Length, c_arg, length); } my_argv[argidx] = c_arg; } } // Initialize MPI int mpi_argc = my_argc; byte** mpi_argv = my_argv; Unsafe.MPI_Init_thread(ref mpi_argc, ref mpi_argv, requiredThreadLevel, out providedThreadLevel); // \todo Copy c-style argc/argv back into args if (mpi_argc != my_argc || mpi_argv != my_argv) { args = new string[mpi_argc]; for (int argidx = 0; argidx < args.Length; ++argidx) { // Find the end of the string int byteCount = 0; while (mpi_argv[argidx][byteCount] != 0) ++byteCount; // Determine how many Unicode characters we need int charCount = ascii.GetCharCount(mpi_argv[argidx], byteCount); // Convert ASCII characters into unicode characters char[] chars = new char[charCount]; fixed (char* argp = chars) { ascii.GetChars(mpi_argv[argidx], byteCount, argp, charCount); } // Create the resulting string args[argidx] = new string(chars); } } } } switch (providedThreadLevel) { case Unsafe.MPI_THREAD_SINGLE: Environment.providedThreadLevel = Threading.Single; break; case Unsafe.MPI_THREAD_FUNNELED: Environment.providedThreadLevel = Threading.Funneled; break; case Unsafe.MPI_THREAD_SERIALIZED: Environment.providedThreadLevel = Threading.Serialized; break; case Unsafe.MPI_THREAD_MULTIPLE: Environment.providedThreadLevel = Threading.Multiple; break; default: throw new ApplicationException("MPI.NET: Underlying MPI library returned incorrect value for thread level"); } // Setup communicators Communicator.world = Intracommunicator.Adopt(Unsafe.MPI_COMM_WORLD); Communicator.self = Intracommunicator.Adopt(Unsafe.MPI_COMM_SELF); } }
public static byte[] Encrypt(string Data) { byte[] result; ASCIIEncoding enc = new ASCIIEncoding (); int numOfChars = enc.GetByteCount (Data); byte[] tempArray = enc.GetBytes (Data); result = SorentoLib.Services.Crypto.ServiceProvider.Encrypt (tempArray, false); return result; }
/// <summary> /// Converts a string to a MemoryStream. /// </summary> static MemoryStream StringToMemoryStream(string s) { System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); int byteCount = enc.GetByteCount(s.ToCharArray(), 0, s.Length); byte[] ByteArray = new byte[byteCount]; int bytesEncodedCount = enc.GetBytes(s, 0, s.Length, ByteArray, 0); System.IO.MemoryStream ms = new System.IO.MemoryStream(ByteArray); return ms; }
public void Send(string data) { if (data == null || data == "") return; ASCIIEncoding encoding = new ASCIIEncoding(); int send = encoding.GetByteCount(data); StateObject so = new StateObject(send+1); encoding.GetBytes(data, 0, send, so.buffer, 0); so.buffer[send] = 0x1a; m_socket.BeginSend(so.buffer, 0, so.buffer.Length, SocketFlags.None, new AsyncCallback(Sent_Callback), so); }
public void NegTest7() { ASCIIEncoding ascii; string source; int charIndex, count; byte[] bytes; int byteIndex; ascii = new ASCIIEncoding(); source = _generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH); charIndex = _generator.GetInt32(-55) % source.Length; count = _generator.GetInt32(-55) % (source.Length - charIndex) + 1; int minLength = ascii.GetByteCount(source.Substring(charIndex, count)); bytes = new byte[minLength]; byteIndex = bytes.Length + _generator.GetInt32(-55) % (int.MaxValue - bytes.Length); DoNegAOORTest(ascii, source, charIndex, count, bytes, byteIndex); }