c# send pdf file from web service - web-services

I am new to C# and I have a web service which generates a pdf file containing barcode(using datamatrix). I want to send this pdf file over to the client as a byte[]
The web service contract is as follows:
[WebInvoke(Method="GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare ,UriTemplate = "/mymethod?param1={param1}&param2={param2}")]
byte[] mymethod(string param1, string param2)
At the client side, I read the response into a memory stream and then convert it into as array and write that to a file.
MemoryStream ms = new MemoryStream();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.GetResponse().GetResponseStream().CopyTo(ms);
byte[] responseBytes = ms.ToArray();
HttpContext.Current.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length);
The data written to the file is something like [37,80,25,....] which is the actual byte[] sent from the web service.
I have gone through many answers here but could not figure out how to get the actual bytes at the client side. Any help would be greatly appreciated.

I figured out the answer myself.
I used a memory stream at the server side and loaded the byte[] into it.
At the client side, I read the memory stream and get the byte[] stored within it.

Related

Google Cloud Platform: Speech to Text Conversion of Large Media Files

I'm trying to extract text from mp4 media file downloaded from youtube. As I'm using google cloud platform so thought to give a try to google cloud speech.
After all the installations and configurations, I copied the following code snippet to get start with:
with io.open(file_name, 'rb') as audio_file:
content = audio_file.read()
audio = types.RecognitionAudio(content=content)
config = types.RecognitionConfig(encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16, sample_rate_hertz=16000, language_code='en-US')
response = client.long_running_recognize(config, audio)
But I got the following error regarding file size:
InvalidArgument: 400 Inline audio exceeds duration limit. Please use a
GCS URI.
Then I read that I should use streams for large media files. So, I tried the following code snippet:
with io.open(file_name, 'rb') as audio_file:
content = audio_file.read()
#In practice, stream should be a generator yielding chunks of audio data.
stream = [content]
requests = (types.StreamingRecognizeRequest(audio_content=chunk)for chunk in stream)
config = types.RecognitionConfig(encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,sample_rate_hertz=16000,language_code='en-US')
streaming_config = types.StreamingRecognitionConfig(config=config)
responses = client.streaming_recognize(streaming_config, requests)
But still I got the following error:
InvalidArgument: 400 Invalid audio content: too long.
So, can anyone please suggest an approach to transcribe an mp4 file and extract text. I don't have any complex requirement of very large media file. Media file can be 10-15 mins long maximum. Thanks
The error message means that the file is too big and you need to first copy the media file to Google Cloud Storage and then specify a Cloud Storage URI such as gs://bucket/path/mediafile.
The key to using a Cloud Storage URI is:
RecognitionAudio audio =
RecognitionAudio.newBuilder().setUri(gcsUri).build();
The following code will show you how to specify a GCS URI for input. Google has a complete example on github.
public static void syncRecognizeGcs(String gcsUri) throws Exception {
// Instantiates a client with GOOGLE_APPLICATION_CREDENTIALS
try (SpeechClient speech = SpeechClient.create()) {
// Builds the request for remote FLAC file
RecognitionConfig config =
RecognitionConfig.newBuilder()
.setEncoding(AudioEncoding.FLAC)
.setLanguageCode("en-US")
.setSampleRateHertz(16000)
.build();
RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(gcsUri).build();
// Use blocking call for getting audio transcript
RecognizeResponse response = speech.recognize(config, audio);
List<SpeechRecognitionResult> results = response.getResultsList();
for (SpeechRecognitionResult result : results) {
// There can be several alternative transcripts for a given chunk of speech. Just use the
// first (most likely) one here.
SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
System.out.printf("Transcription: %s%n", alternative.getTranscript());
}
}
}

Send Binary Image Data Over WebSockets In C++

I am looking to send image data in binary format from a C++ WebSockets server to the browser and then have the browser to interpret the data to display the image to the end user.
Here is my C++ code to read image and send data -
WebsocketClient& client = (WebsocketClient&) (*pClient);
WebsocketDataMessage response(EchoCommunication);
FILE *img = fopen("test_image.png", "rb");
fseek(img, 0, SEEK_END);
unsigned long filesize = ftell(img);
char *buffer = (char*)malloc(sizeof(char)*filesize);
rewind(img);
while (!feof(img)) {
fread(buffer, 1, sizeof(buffer), img);
response.SetArguments(buffer);
}
client.PushPacket(&response);
In Chrome Network tab I am able to see binary frames being received but having no luck in displaying image in browser. I have doubts if data being sent is valid.
Please let me know where am I going wrong.

AES encryption in game server client/server

I run a game server, i got main server that handles all packets sent from players (clients).
I want to encrypt my packets via AES so that each packet should be unique (i think i need IV here) and that server should accept each encrypted packet one time only, so that if someone tried to sniff a packet he cannot send it again.
How do I do this?
P.S i code server and client in c++
You could use some kind of SSL API like OpenSSL, but this may be overkill in your scenario as you would need to use certificates etc. There is a open source Rijndael (the algorithm that AES uses) C++ implementation here.
Here is an example of its usage:
void testEncryptBlock()
{
const int nCharacters = 16;
char szHex[33];
char *EncryptedData = new char[nCharacters + 1];
CRijndael rijndael;
int result = rijndael.MakeKey("abcdefghabcdefghabcdefghabcdefgh");
// Add some dummy data for the sake of the demo
EncryptedData = (char*)memset(EncryptedData, 255, nCharacters); // 0xfffff...
result = rijndael.EncryptBlock(EncryptedData);
... // Do something with the data
delete [] EncryptedData;
}

Play 2 WS, how to detect interrupted or corrupt download?

My service occasionally fetches some content (mostly image files) in batches (20 at a time), in a concurrent manner. Sometimes, some of these image files end up corrupted (browser doesn't render them), not sure why, but it only happens when downloading in larger batches. How to check programmatically if the download was corrupted so I can restart it?
I use Play2 WS on Scala. Iteratees not used.
stackoverflow.com/questions/304268/getting-a-files-md5-checksum-in-java
try retrieving the md5 checksum. would that work for you?
Use DigestUtils from Apache Commons Codec library:
FileInputStream fis = new FileInputStream(new File("foo"));
String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);

GZipStream over .NET webservice causes invalid character issue

I'm working on a complex .NET client server architecture customization and I absolutely have no control over request/reply sent or received except that I can add my stuff to the request/reply objects.
I've a dataset on server side to be sent to client andI'm using GZipStream to compress the dataset. The compression works fine, but when the reply is received on client end, I get invalid character exception - 0x1F. I googled and could not find appropriate resource to address this issue.
Compression code:
Private Function Compress(ByVal data() As Byte) As Byte()
Try
'---the ms is used for storing the compressed data---
Dim ms As New MemoryStream()
Dim zipStream As Stream = Nothing
zipStream = New GZipStream(ms, _
CompressionMode.Compress, True)
'---or---
'zipStream = New DeflateStream(ms, _
' CompressionMode.Compress, True)
'---compressing using the info stored in data---
zipStream.Write(data, 0, data.Length)
zipStream.Close()
ms.Position = 0
'---used to store the compressed data (byte array)---
Dim compressed_data(CInt(ms.Length - 1)) As Byte
'---read the content of the memory stream into
' the byte array---
ms.Read(compressed_data, 0, CInt(ms.Length))
Return compressed_data
Catch ex As Exception
Return Nothing
End Try
End Function
Any idea to fix this issue considering the fact that I can alter the request/response handling mechanism is really appreciated. In addition, I also request any ideas on better ways handling large dataset transfers over webservice. Thank you.