SslStream.DataAvailable not a valid function - c#

I am migrating C# code from using a NetworkStream to SSLStream, however where I use stream.DataAvailable I get the error:
Error 1 'System.Net.Security.SslStream'
does not contain a definition for
'DataAvailable' and no extension
method 'DataAvailable' accepting a
first argument of type
'System.Net.Security.SslStream' could
be found (are you missing a using
directive or an assembly reference?)
now my local MSDN copy does not include DataAvailable as a member of SslStream however http://msdn.microsoft.com/en-us/library/dd170317.aspx says it does have the member DataAvailable.
here is a copy of my code.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.IO;
namespace Node
{
public static class SSLCommunicator
{
static TcpClient client = null;
static SslStream stream = null;
static List<byte> networkStreamInput = new List<byte>();
public static void connect(string server, Int32 port)
{
try
{
client = new TcpClient(server, port);
stream = new SslStream(client.GetStream(),false);
...
...
...
public static List<DataBlock> getServerInput()
{
List<DataBlock> ret = new List<DataBlock>();
try
{
//check to see if stream is readable.
if (stream.CanRead)
{
//Check to see if there is data available.
if (stream.DataAvailable)
{
byte[] readBuffer = new byte[1024];
int numberOfBytesRead = 0;
//while data is available buffer the data.
do
{
numberOfBytesRead = stream.Read(readBuffer, 0, readBuffer.Length);
byte[] tmp = new byte[numberOfBytesRead];
Array.Copy(readBuffer, tmp, numberOfBytesRead);
networkStreamInput.AddRange(tmp);
} while (stream.DataAvailable);
...
Also if you have a better way to get my output of the stream in to a managed array (there will be some parsing done on it later in the code) I would love the help. I am using Visual Studio 2008
--EDIT
I just realized I linked to the embedded SDK, this is not a embedded system, so how do I see if data is available in the normal .net SDK?

The page you are looking at is for the .NET Micro Framework.
According to this page for .Net 2.0 and this page for .Net 3.5, there is no DataAvailable property on SSLStream.
Edit: Can't you just call Read() and see if you get anything back? i don't think this will block.

Related

c# BigInteger to 32 byte hex

I need to get from a biginteger to a 32 byte hex value. To use in the third parameter on this description:
My current code is not generating a valid hex value.
public static string GetTargetHex(BigInteger difficulty)
{
// 2^256 / difficulty.
var target = BigInteger.Divide(BigInteger.Pow(2, 256), difficulty);
return $"0x{target.ToString("X16").ToLower()}";
}
All I have to go by for now is knowing that a value of 23142114022743 results in a hex value of '0x00000000000c29b321174712bb7ca6dd0896b050e18d4c7e13df4c1aee84f2c0'.
Ethereum has their own standard for Hex encoding / decoding.
You can use Nethereum for this.
From the screen shot to get your work:
using System;
using System.Text;
using Nethereum.Hex.HexConvertors.Extensions;
using System.Threading.Tasks;
using Nethereum.Web3;
using Nethereum.RPC.Eth.Blocks;
using Nethereum.Hex.HexTypes;
public class HexDecoding
{
private static async Task Main(string[] args)
{
var web3 = new Web3("your url");
var work = await web3.Eth.Mining.GetWork.SendRequestAsync();
Console.WriteLine(work.Length);
}
}
And to do the calculation, depending in your endianism you can do something like this:
using System;
using System.Text;
using Nethereum.Hex.HexConvertors.Extensions;
using System.Threading.Tasks;
using Nethereum.Web3;
using Nethereum.RPC.Eth.Blocks;
using Nethereum.Hex.HexTypes;
using System.Numerics;
public class HexDecoding
{
private static async Task Main(string[] args)
{
var difficulty = 23142114022743;
var target = BigInteger.Divide(BigInteger.Pow(2, 256), difficulty);
Console.WriteLine(target);
// A simple check on endianism and reversing
byte[] bytes;
Console.WriteLine(BitConverter.IsLittleEndian);
if (BitConverter.IsLittleEndian)
bytes = target.ToByteArray().Reverse().ToArray();
else
bytes = target.ToByteArray().ToArray();
Console.WriteLine(bytes.ToHex());
//Another option using .Net core now (awesome)
Console.WriteLine(target.ToByteArray(true, true).ToHex()); // new .net core
//Final option if you are using Nethereum and not using .Net core
Console.WriteLine(HexBigIntegerConvertorExtensions.ToByteArray(target, false).ToHex());
//0x00000000000c29b321174712bb7ca6dd0896b050e18d4c7e13df4c1aee84f2c0
//0x00000000000c29b321174712bb7ca6dd0896b050e18d4c7e13df4c1aee84f2c0
}
}

simple program to convert image to byte array in c# and display that array

here is my program that i have written
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Data;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
Image img = Image.FromFile("C:\\images.JPG");
byte[] bArr = imgToByteArray(img);
}
public byte[] imgToByteArray(System.Drawing.Image Imagein)
{
byte[] data = null;using (System.IO.MemoryStream ms = new MemoryStream())
{
Imagein.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
data = ms.ToArray();
}
return data;
}
}
}
now when i build the program it shows error
an object reference is required for the non static field, method or property 'Program.imgToByteArray(Image)'
The error is pretty clear, you can't access non static methods in a static context (method).
You have two options to fix this issue.
Option 1
Make your function/method a static function.
public static byte[] imgToByteArray(System.Drawing.Image Imagein)
{
...
}
Option 2:
Create an instance of Program and access the method.
new Program().imgToByteArray(img);
Since you want to print byte array in console (not sure why?) you could do something like this.
Console.WriteLine(string.Join(",", bytearray);
Make the imgToByteArray method static.
There is really no other rational option.
Regarding Option 2 from #Hari Prasad answer you considered an "possible option": You would be creating new class instance to call a member of this instance from a static class member that is the main entry point of the application which is pretty hardcore and given the code design guildelines i.e. https://msdn.microsoft.com/en-us/library/ms245046.aspx it is something you shouldn't.

What using statement do I need for WavReader and FlacWriter?

so far I have these using statements:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using System.Threading;
using NAudio.Wave;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using Alvas.Audio;
I'm trying to write a wav to flac converter.
Here is the function:
public static void flac_converter()
{
string inputFile = Path.Combine("wav ", input);
string outputFile = Path.Combine("flac", Path.ChangeExtension(input, ".flac"));
if (!File.Exists(inputFile))
throw new ApplicationException("Input file " + inputFile + " cannot be found!");
WavReader wav = new WavReader(inputFile);
using (var flacStream = File.Create(outputFile))
{
FlacWriter flac = new FlacWriter(flacStream, wav.BitDepth, wav.Channels, wav.SampleRate);
// Buffer for 1 second's worth of audio data
byte[] buffer = new byte[wav.Bitrate / 8];
int bytesRead;
do
{
bytesRead = wav.InputStream.Read(buffer, 0, buffer.Length);
flac.Convert(buffer, 0, bytesRead);
} while (bytesRead > 0);
flac.Dispose();
flac = null;
}
}
But I get this error: "The Type of Namespace 'WavReader' cannot be found"
I also get this error: "The Type or Namespace 'FlacWriter' cannot be found"
I know I have to do two things, download the appropriate lib, then all teh DLL files to the reference of the project and also add "using blahBlah;"
However, I don't know what DLL i need, or what using statements I need to get rid of these errors. Anyone know?
change the spelling of wavreader to wavereader. It should work out.

NAudio Object reference not set to an instance of an object

Referring to this question, I have used the code from it: Play audio from a stream using C#
However, I get an error "Object reference not set to an instance of an object" running in debug. I have assigned Url's to a combo box, and when I choose the first choice, opening an ASX stream, the program crashes, giving me the above in debugger.
Any ideas? I have tried doing some fixing with the code below, but I don't think I'm getting the idea, since it still isn't working.
Edit:// It doesn't recognize Mp3FileReader however there are no errors/warnings, it isn't green as it normally would be, am I missing a library?
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;
using System.IO;
using System.Net;
using NAudio.Wave;
using NAudio;
public static void PlayMp3FromUrl(string url)
{
using (Stream ms = new MemoryStream())
{
using (Stream stream = WebRequest.Create(url).GetResponse().GetResponseStream())
{
byte[] buffer = new byte[32768];
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
}
ms.Position = 0;
Mp3FileReader fr = new Mp3FileReader(ms);
WaveStream blockAlignedStream = new BlockAlignReductionStream(WaveFormatConversionStream.CreatePcmStream(fr));
if(ms != null)
{
using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
{
waveOut.Init(blockAlignedStream);
waveOut.Play();
while (waveOut.PlaybackState == PlaybackState.Playing)
{
System.Threading.Thread.Sleep(100);
}
}
}
else
{
MessageBox.Show("blockAlignedStream variable was null!");
}
}
}
The code sample you are using is not a good example of how to play an MP3 from a stream. There are multiple problems with the code. Either use the technique described in this article, or you may be able to make use of the new MediaFoundationReader which can play from a URL.

How to deserialize a file received from the network

I'm working on a software i need some help.
I have a client and server. Server will serialize a text file and send it to the client.
My current progress: Client receiving binary array but can't write it to disc as original text file.
private void ListenPort()
{
TcpListener _TcpListener= new _TcpListener(7381);
byte[] received_binary= new byte[1024];
_TcpListener.Start();
while (true)
{
Socket Soket = _TcpListener.AcceptSocket();
Soket.Receive(received_binary, received_binary.Length, 0);
}
}
Do you need to deserialize it to string? Here is a function I wrote a while ago which may help...
public static T BinaryDeserializeObject<T>(byte[] serializedType)
{
if (serializedType == null)
throw new ArgumentNullException("serializedType");
if (serializedType.Length.Equals(0))
throw new ArgumentException("byte array cannot be empty"));
T deserializedObject;
using (MemoryStream memoryStream = new MemoryStream(serializedType))
{
BinaryFormatter deserializer = new BinaryFormatter();
deserializedObject = (T)deserializer.Deserialize(memoryStream);
}
return deserializedObject;
}
The main issue seems to be that you are ignoring the return value from receive. This returns the number of bytes in each read. You should loop until this is non-positive, each time processing (for example writing to a FileStream) that many bytes (only: even if the buffer is larger).
One possible solution is to load the text file either as a series of strings or as a byte array and send that. The byte array approach might be the most concise and efficient, as it can be compressed during send, using the network library networkcomms.net the application calling the sending would look something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetworkCommsDotNet;
namespace Client
{
class Program
{
static void Main(string[] args)
{
byte[] bytesToSend = File.ReadAllBytes("testFile.txt");
TCPConnection.GetConnection(new ConnectionInfo("127.0.0.1", 10000)).SendObject("TextFileData", bytesToSend);
Console.WriteLine("Press any key to exit client.");
Console.ReadKey(true);
NetworkComms.Shutdown();
}
}
}
and the server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetworkCommsDotNet;
namespace Server
{
class Program
{
static void Main(string[] args)
{
NetworkComms.AppendGlobalIncomingPacketHandler<byte[]>("TextFileData", (packetHeader, connection, incomingData) =>
{
Console.WriteLine("Received TextFileData");
File.WriteAllBytes("testFile.txt", incomingData);
});
TCPConnection.StartListening(true);
Console.WriteLine("Server ready. Press any key to shutdown server.");
Console.ReadKey(true);
NetworkComms.Shutdown();
}
}
}
You will obviously need to download the NetworkCommsDotNet DLL from the website so that you can add it in the 'using NetworkCommsDotNet' reference. Also see the server IP address in the client example is currently "127.0.0.1", this should work if you run both the server and client on the same machine. For more information also checkout the getting started or how to create a client server application articles.

Categories