Web Service returned error : Not Found - c#

The web service i am using returned web exception. Service is called from Silverlight application. Basically i am trying to convert eps file into png . On localhost everything is working well but when i deployed on web server i am getting this error.
Silverlight Code is --
private void btnUploadImage_Click(object sender, RoutedEventArgs e)
{
string fileextn = string.Empty;
OpenFileDialog openDialog = new OpenFileDialog();
if (openDialog.ShowDialog() == true)
{
try
{
string fileExtension = openDialog.File.Extension.ToString();
if (fileExtension.Contains("jpeg") || fileExtension.Contains("jpg") || fileExtension.Contains("png") || fileExtension.Contains("tif") || fileExtension.Contains("tiff") || fileExtension.Contains("bmp") || fileExtension.Contains("gif"))
{
using (Stream stream = openDialog.File.OpenRead())
{
HtmlPage.Window.Invoke("showProcessingAndBlockUI");
// Don't allow really big files (more than 2 MB).
if (stream.Length < 5 * 1024 * 1025)
{
MemoryStream tempStream = new MemoryStream();
byte[] data = new byte[stream.Length];
stream.Position = 0;
stream.Read(data, 0, (int)stream.Length);
tempStream.Write(data, 0, (int)stream.Length);
stream.Close();
ProductConfiguratorServiceClient pcs = new ProductConfiguratorServiceClient();
string virtualpath = HelperClass.GetVirtual();
pcs.Endpoint.Address = new System.ServiceModel.EndpointAddress(virtualpath + "/Services/ProductConfiguratorService.svc/basic");
pcs.GetFormattedImageCompleted += new EventHandler<GetFormattedImageCompletedEventArgs>(pcs_GetFormattedImageCompleted);
pcs.GetFormattedImageAsync(data);
pcs.CloseAsync();
tempStream.Close();
}
else
{
MessageBox.Show("Files must be less than 5 MB.");
}
}
}
else if (openDialog.File.Extension.Contains("eps"))
{
HtmlPage.Window.Invoke("showProcessingAndBlockUI");
using (Stream stream = openDialog.File.OpenRead())
{
if (stream.Length < 5 * 1024 * 1025)
{
MemoryStream tempStream = new MemoryStream();
byte[] data = new byte[stream.Length];
stream.Position = 0;
stream.Read(data, 0, (int)stream.Length);
tempStream.Write(data, 0, (int)stream.Length);
stream.Close();
ProductConfiguratorServiceClient pcs = new ProductConfiguratorServiceClient();
string virtualpath = HelperClass.GetVirtual();
pcs.Endpoint.Address = new System.ServiceModel.EndpointAddress(virtualpath + "/Services/ProductConfiguratorService.svc/basic");
pcs.GetEpsFileIntoPngCompleted += new EventHandler<GetEpsFileIntoPngCompletedEventArgs>(pcs_GetEpsFileIntoPngCompleted);
pcs.GetEpsFileIntoPngAsync(data);
tempStream.Close();
}
else
{
MessageBox.Show("Files must be less than 5 MB.");
}
}
}
else
{
MessageBox.Show("Please Check the Image Format.");
}
}
catch (Exception)
{
HtmlPage.Window.Invoke("hideBlockUI");
MessageBox.Show("Somr Error Occured, Please Try Again Later .");
}
}
}
void pcs_GetEpsFileIntoPngCompleted(object sender, GetEpsFileIntoPngCompletedEventArgs e)
{
busi.CurrentlySelectedOverlayImage.UploadedImageStream = e.Result;
busi.CurrentlySelectedOverlayImage.ImageFileType = "png";
RefreshStatus();
busi.CurrentlySelectedOverlayImageChanged = true;
HtmlPage.Window.Invoke("hideBlockUI");
}
void pcs_GetFormattedImageCompleted(object sender, GetFormattedImageCompletedEventArgs e)
{
try
{
if (e.Error != null)
{
MessageBox.Show(e.Error.ToString());
}
else
{
busi.CurrentlySelectedOverlayImage.UploadedImageStream = e.Result;
busi.CurrentlySelectedOverlayImage.ImageFileType = "jpeg";
RefreshStatus();
busi.CurrentlySelectedOverlayImageChanged = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
//throw new NotImplementedException();
}
Error is at System.Net.Browser.BrowserHttpWebRequest.
Please assist me whether what kind of problem is this?

It could have something to do with this line.
pcs.Endpoint.Address = new System.ServiceModel.EndpointAddress(virtualpath +
You are missing the rest of it.
Pretty sure this is a compile error though.
So either this error is getting eaten and the generic one is popping up or you have some other issue along with this.

Related

C# - Amazon Lex chatbot voice input [duplicate]

I have the chatbot client running with text but would now like to change it to voice but I am unsure of how to get the stream from the mic for post. For recording audio I am using NAudio but when sending the memory stream I get an error stating
System.IO.IOException: Cannot close stream until all bytes are
written.
Here is my code:
private void recordAudio()
{
if (memoryStream == null)
memoryStream = new MemoryStream();
sourceStream = new NAudio.Wave.WaveIn();
sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(16000, 1);
waveIn = new NAudio.Wave.WaveInProvider(sourceStream);
waveWriter = new WaveFileWriter(new IgnoreDisposeStream(memoryStream), waveIn.WaveFormat);
sourceStream.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(sourceStream_DataAvailable);
buff = new BufferedWaveProvider(waveIn.WaveFormat);
sourceStream.StartRecording();
mytimer.Enabled = true;
}
private void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
{
buff.AddSamples(e.Buffer, 0, e.BytesRecorded);
Console.WriteLine("test");
}
void mytimer_Tick(object sender, EventArgs e)
{
if (sourceStream != null)
{
sourceStream.StopRecording();
waveWriter.Flush();
var amazonLexClient = new AmazonLexClient(Amazon.RegionEndpoint.USEast1);
var amazonPostRequest = new Amazon.Lex.Model.PostContentRequest();
var amazonPostResponse = new Amazon.Lex.Model.PostContentResponse();
amazonPostRequest.BotAlias = "voiceBot";
amazonPostRequest.BotName = "voiceBot";
amazonPostRequest.ContentType = "audio/l16; rate=16000; channels=1";
amazonPostRequest.UserId = "user";
amazonPostRequest.InputStream = memoryStream;
amazonPostRequest.UserId = "test";
try
{
amazonPostResponse = amazonLexClient.PostContent(amazonPostRequest);
Console.WriteLine("Got a response");
}
catch (Exception w)
{
Console.WriteLine("{0} Exception caught.", e);
Console.WriteLine(w.Message);
}
You have to set the Position of your MemoryStream to 0 before you pass it to the post request.
memoryStream.Position = 0;

Streaming FFMPEG RTSP in C#

I wish to stream an RTSP feed from my camera through my C# client app and eventually recieve it on my server.
To test it I decided to stream it through my client and then recieve the jpeg frames from it as well.
I 1st tested my command line arguments in a DOS window.
It worked in that it stream to an output file without incident.
So, now I ported it over to my C# app and used the Process Class.
This is the code:
Task.Run(() =>
{
try
{
process.Start();
byte[] buffer = new byte[200000];
baseStream = process.StandardOutput.BaseStream as FileStream;
bool gotHeader = false;
bool imgFound = false;
int counter = 0;
while (true)
{
byte bit1 = (byte)baseStream.ReadByte();
buffer[counter] = bit1;
if (bit1 == 217 && gotHeader)
{
if (buffer[counter - 1] == 255)
{
byte[] jpeg = new byte[counter];
Buffer.BlockCopy(buffer, 0, jpeg, 0, counter);
using (MemoryStream ms = new MemoryStream(jpeg))
{
pictureBox1.Image = Image.FromStream(ms);
ms.Close();
}
imgFound = true;
}
}
else if (bit1 == 216)
{
if (buffer[counter - 1] == 255)
{
gotHeader = true;
}
}
if (imgFound)
{
counter = 0;
buffer = new byte[200000];
imgFound = false;
gotHeader = false;
}
else
{
counter++;
}
}
}
catch (Exception ex2)
{
//log error here
}
});
But I do not get any images I just get the byte value of 255 at this line:
buffer[counter] = bit1;
So.. what am I doing wrong please?
Thanks

TcpClient performance on Xamarin.Android

I have encountered a problem with TcpClient running on an Android device. The issue is that reading from NetworkStream takes a lot of time. I use it to send bitmaps from server application (also written in C#) to my Android device (Nexus 9). I push 6000 bitmaps each of them around 1.4KB in size. That takes around 30 seconds to complete (5ms per bitmap). On the other hand I also implemented the same in Java and it takes 5 seconds to do the same (less than 1ms per bitmap)!
Are you aware of any issues regarding TcpClient in Xamarin.Android? I have to admit that this is very surprising as I have never had similar problems with Xamarin.
I pasted just a little code below so you can take a look if it is not me that messed up something. At the very bottom I also pasted Java code and as you can see it is very similar. Do you have any suggestions regarding this? I appreciate any feedback.
Here is the method that I use to receive bitmaps (this function runs asynchronously and is started through Task.Factory.StartNew()):
private void HandleRequestBitmaps(TcpClient client, CancellationToken token)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
var encoder = new UTF8Encoding();
using (var stream = client.GetStream())
{
stream.WriteMessageWithLength(ServerCommand.PushBitmaps.ServerCommandToBytes(encoder));
var initialMetadataBytes = stream.ReadMessageWithLength(client.ReceiveBufferSize);
int[] initialMetadata;
if (!TryParseMetadataMessage(initialMetadataBytes, encoder, 3, out initialMetadata))
{
BitmapReceiveEnd(this, new BitmapReceiveEndEventArgs(false));
return;
}
BitmapsReceiveBegin(this,
new BitmapsReceiveBeginEventArgs(initialMetadata[0], initialMetadata[1], initialMetadata[2]));
while (!token.IsCancellationRequested)
{
var messageBytes = stream.ReadMessageWithLength(client.ReceiveBufferSize);
if (ServerCommand.PushBitmapsDone.Equals(messageBytes.BytesToServerCommand(encoder)))
{
BitmapReceiveEnd(this, new BitmapReceiveEndEventArgs(true));
break;
}
int[] metadata;
if (!TryParseMetadataMessage(messageBytes, encoder, 3, out metadata))
{
BitmapReceiveEnd(this, new BitmapReceiveEndEventArgs(false));
return;
}
var bitmapBytes = stream.ReadMessageWithLength(client.ReceiveBufferSize);
BitmapReceived(this,
new BitmapReceivedEventArgs(metadata[0], new Point(metadata[1], metadata[2]), bitmapBytes));
}
}
}
Where TryParseMetadaMessage method looks like this:
private static bool TryParseMetadataMessage(byte[] message, Encoding encoder, int expectedLength,
out int[] metadata)
{
var messageString = encoder.GetString(message, 0, message.Length);
var messageStringSeparated = messageString.Split('x');
if (messageStringSeparated.Length != expectedLength)
{
metadata = new int[0];
return false;
}
var parameteres = new List<int>();
foreach (var messageStringPart in messageStringSeparated)
{
int value;
if (!int.TryParse(messageStringPart, out value))
{
metadata = new int[0];
return false;
}
parameteres.Add(value);
}
metadata = parameteres.ToArray();
return true;
}
}
Also ReadMessage with length looks like this:
public static byte[] ReadMessageWithLength(this Stream stream, int bufferSize = 2048)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
var messageSizeBuffer = new byte[4];
if (stream.Read(messageSizeBuffer, 0, messageSizeBuffer.Length) < 1)
{
return new byte[0];
}
if (BitConverter.IsLittleEndian)
{
Array.Reverse(messageSizeBuffer);
}
var totalBytesToRead = BitConverter.ToInt32(messageSizeBuffer, 0);
if (totalBytesToRead < 0)
{
throw new Exception("Number of bytes to read cannot be negative!");
}
using (var memoryStream = new MemoryStream())
{
var buffer = new byte[bufferSize];
int chunkBytesRead, totalBytesRead = 0;
while (
(chunkBytesRead = stream.Read(buffer, 0, Math.Min(totalBytesToRead - totalBytesRead, buffer.Length))) >
0)
{
memoryStream.Write(buffer, 0, chunkBytesRead);
totalBytesRead += chunkBytesRead;
if (totalBytesRead >= totalBytesToRead)
{
break;
}
}
return memoryStream.ToArray();
}
}
Now time for Java code. The function used to receive bitmaps:
public void requestBitmaps() {
if (socket == null || !socket.isConnected()) {
throw new IllegalStateException("Socket has to be initialized and connected to call this method!");
}
requestBitmapsThread = new Thread(new Runnable() {
#Override
public void run() {
try {
InputStream sis = new BufferedInputStream(socket.getInputStream());
OutputStream sos = new BufferedOutputStream(socket.getOutputStream());
writeMessageWithLength(sos, ServerCommand.PushBitmaps.getValueBytes());
byte[] initialMetadataBytes = readMessageWithLength(sis, socket.getReceiveBufferSize());
int[] initialMetadata = parseMetadataMessage(initialMetadataBytes, 3);
if (initialMetadata == null) {
listener.onBitmapReceivedEnd(false);
return;
}
listener.onBitmapReceivedBegin(initialMetadata[0], initialMetadata[1], initialMetadata[2]);
while (!Thread.currentThread().isInterrupted()) {
byte[] messageBytes = readMessageWithLength(sis, socket.getReceiveBufferSize());
if (ServerCommand.PushBitmapsDone.equals(ServerCommand.fromValueBytes(messageBytes))) {
listener.onBitmapReceivedEnd(true);
break;
}
int[] metadata = parseMetadataMessage(messageBytes, 3);
if (metadata == null) {
listener.onBitmapReceivedEnd(false);
break;
}
byte[] bitmapBytes = readMessageWithLength(sis, socket.getReceiveBufferSize());
listener.onBitmapReceived(metadata[0], metadata[1], metadata[2], bitmapBytes);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
requestBitmapsThread.start();
}
And also parseMetadataMessage method:
private int[] parseMetadataMessage(byte[] metadataBytes, int expectedLength) {
String metadataString = new String(metadataBytes, Charset.forName("UTF-8"));
String[] metadataStringSeparated = metadataString.split("x");
if (metadataStringSeparated.length != expectedLength) {
return null;
}
try {
int[] parameters = new int[metadataStringSeparated.length];
for (int i = 0; i < metadataStringSeparated.length; i++) {
parameters[i] = Integer.parseInt(metadataStringSeparated[i]);
}
return parameters;
} catch (NumberFormatException e) {
e.printStackTrace();
return null;
}
}
And readMessageWithLength:
private byte[] readMessageWithLength(InputStream is, int bufferLength) throws IOException {
byte[] messageLengthBuffer = new byte[4];
if (is.read(messageLengthBuffer) < 0) {
return null;
}
ByteBuffer messageLengthByteBuffer = ByteBuffer.wrap(messageLengthBuffer).order(ByteOrder.BIG_ENDIAN);
int totalBytesToRead = messageLengthByteBuffer.getInt();
if (totalBytesToRead < 0) {
throw new IllegalStateException("Total bytes to read cannot be less than 0!");
}
ByteArrayOutputStream bitmapBytesBuffer = null;
try {
bitmapBytesBuffer = new ByteArrayOutputStream();
byte[] buffer = new byte[bufferLength];
int chunkBytesRead, totalBytesRead = 0;
while ((chunkBytesRead = is.read(buffer, 0, Math.min(totalBytesToRead - totalBytesRead, buffer.length))) > 0) {
bitmapBytesBuffer.write(buffer, 0, chunkBytesRead);
totalBytesRead += chunkBytesRead;
if (totalBytesRead >= totalBytesToRead) {
break;
}
}
return bitmapBytesBuffer.toByteArray();
} finally {
if (bitmapBytesBuffer != null) {
bitmapBytesBuffer.close();
}
}
}
If you have come this far, thanks for attention. I appreciate any feedback and I hope it will be possible to speed up the code.
Best regards,
Bartosz

Unzip files in Windows Phone 8 - 'System.OutOfMemoryException'

I used the UnZipper class from this (How to unzip files in Windows Phone 8) post in my app for zips with images, but in some rare cases it gives me this error:
A first chance exception of type 'System.OutOfMemoryException' occurred in System.Windows.ni.dll System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown. at System.Windows.Application.GetResourceStreamInternal(StreamResourceInfo zipPackageStreamResourceInfo, Uri resourceUri) at System.Windows.Application.GetResourceStream(StreamResourceInfo zipPackageStreamResourceInfo, Uri uriResource) at ImperiaOnline.Plugins.UnZipper.GetFileStream(String filename) at ImperiaOnline.Plugins.IOHelpers.unzip(String zipFilePath, String zipDestinationPath)
The device has more then twice needed free memory. Can somebody help me with this. Here is my code:
public static void unzip(string zipFilePath,string zipDestinationPath) {
using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
var dirNames = isolatedStorage.GetDirectoryNames(zipDestinationPath);
bool doesFolderExists = (dirNames.Length > 0) ? true : false;
if (!doesFolderExists)
{
Debug.WriteLine("Folder does not exists");
isolatedStorage.CreateDirectory(zipDestinationPath);
}
try
{
using (IsolatedStorageFileStream zipFile = isolatedStorage.OpenFile(zipFilePath, FileMode.Open, FileAccess.ReadWrite))
{
UnZipper unzip = new UnZipper(zipFile);
bool isModuleFolderDeleted = false;
foreach (string currentFileAndDirectory in unzip.FileNamesInZip())
{
string[] fileLocations = currentFileAndDirectory.Split('/');
string prefix = zipDestinationPath + '/';
int locationsCount = fileLocations.Length;
string fileName = fileLocations.Last();
string currentPath = prefix;
for (int i = 0; i < locationsCount - 1; i++)
{
dirNames = isolatedStorage.GetDirectoryNames(currentPath + fileLocations[i]);
doesFolderExists = (dirNames.Length > 0) ? true : false;
if (!doesFolderExists)
{
isolatedStorage.CreateDirectory(currentPath + fileLocations[i]);
if (i == 2)
{
isModuleFolderDeleted = true;
}
}
else if (i == 2 && !isModuleFolderDeleted)
{
Debug.WriteLine(currentPath + fileLocations[i] + " is deleted and recreated");
DeleteDirectoryRecursively(isolatedStorage, currentPath + fileLocations[i]);
isolatedStorage.CreateDirectory(currentPath + fileLocations[i]);
isModuleFolderDeleted = true;
}
currentPath += fileLocations[i] + '/';
}
var newFileStream = isolatedStorage.CreateFile(currentPath + fileName);
byte[] fileBytes = new byte[unzip.GetFileStream(currentFileAndDirectory).Length];
unzip.GetFileStream(currentFileAndDirectory).Read(fileBytes, 0, fileBytes.Length);
unzip.GetFileStream(currentFileAndDirectory).Close();
try
{
newFileStream.Write(fileBytes, 0, fileBytes.Length);
}
catch (Exception ex)
{
Debug.WriteLine("FILE WRITE EXCEPTION: " + ex);
newFileStream.Close();
newFileStream = null;
zipFile.Close();
unzip.Dispose();
}
newFileStream.Close();
newFileStream = null;
}
zipFile.Close();
unzip.Dispose();
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
isolatedStorage.DeleteFile(zipFilePath);
}
}
This error appears here:
var newFileStream = isolatedStorage.CreateFile(currentPath + fileName);
byte[] fileBytes = new byte[unzip.GetFileStream(currentFileAndDirectory).Length]; unzip.GetFileStream(currentFileAndDirectory).Read(fileBytes, 0, fileBytes.Length);
unzip.GetFileStream(currentFileAndDirectory).Close();
I debugged it and it fails on
byte[] fileBytes = new byte[unzip.GetFileStream(currentFileAndDirectory).Length];
I checked GetFileStream method
public Stream GetFileStream(string filename)
{
if (fileEntries == null)
fileEntries = ParseCentralDirectory(); //We need to do this in case the zip is in a format Silverligth doesn't like
long position = this.stream.Position;
this.stream.Seek(0, SeekOrigin.Begin);
Uri fileUri = new Uri(filename, UriKind.Relative);
StreamResourceInfo info = new StreamResourceInfo(this.stream, null);
StreamResourceInfo stream = System.Windows.Application.GetResourceStream(info, fileUri);
this.stream.Position = position;
if (stream != null)
return stream.Stream;
return null;
}
It throws OutOfMemory exception on this row:
StreamResourceInfo stream = System.Windows.Application.GetResourceStream(info, fileUri);

Send parts of a byte[] by webclient to create a large file in server side

So trying to Transfer a large byte[] for that chose to separate it in chunks of 20MB, and in the first chunk received create the file and add that,the rest open the existing file and add the remaining.The problem that I am having is instead of send the first part and reconnect to receive the second part its establishing the two connections and sending the two chunks at the same time.. how can send the second after the first as finished?
client.OpenWriteAsync(ub.Uri);
void client_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("Cancelled");
}
else if (e.Error != null)
{
MessageBox.Show("Deu erro");
}
else
{
try
{
using (Stream output = e.Result)
{
int countbytes;
//for (int i = 0; i < max; i++)
//{
if ( (max+1) != maxAux)
{
countbytes = zippedMemoryStream.Read(PartOfDataSet, 0 , 20000000);//maxAux * 20000000
output.Write(PartOfDataSet, 0, (int)countbytes);
if (max != maxAux)
{
client.OpenWriteAsync(ub.Uri);
}
maxAux++;
}
//}
//numeroimagem++;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
//throw;
}
}
}
public void ProcessRequest(HttpContext context)
{
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
string ImageName = context.Request.QueryString["ImageName"];
string UploadPath = context.Server.MapPath("~/ServerImages/");
byte[] bytes = new byte[20000000];
int bytesToRead = 0;
if (!File.Exists(UploadPath + ImageName))
{
using (FileStream stream = File.Create(UploadPath + ImageName))
{
try
{
//List<byte> bytes = new List<byte>();
while ((bytesToRead =
context.Request.InputStream.Read(bytes, 0, bytes.Length)) != 0)
//context.Request.InputStream.Read(bytes, 0, 200000)) != 0)
{
stream.Write(bytes, 0, bytesToRead);
stream.Close();
}
bytes = null;
}
catch (Exception ex)
{
string error = ex.Message;
throw;
}
}
}
else
{
using (FileStream stream = File.Open(UploadPath + ImageName,FileMode.Append))
{
try
{
while ((bytesToRead =
context.Request.InputStream.Read(bytes, 0, bytes.Length)) != 0)
{
stream.Write(bytes, 0, bytesToRead);
stream.Close();
}
bytes = null;
}
catch (Exception ex)
{
string error = ex.Message;
throw;
}
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
In fact you gain nothing by opening the client again. You can just loop over your zippedMemoryStream in chunks and write it to the output stream. Then the data will arrive in order on the server side.
Otherwise look into the UploadData methods, if you really want to create a new connection each time.

Categories

Resources