How to save byte[] as wav file in silverlight application? - c#

In my MVC Application I added a Silverlight Audio Recorder. This recorder record audio using System.Windows.Media; namespace as byte[] that represents an wav file.
Now I need to save this byte[] as .wav file on local disk (server).
So far I've tried the following:
byte[] audioData; // Here I contain my data
System.IO.File.WriteAllBytes(#"C:\Temp\yourfile.wav", this.audioData); // Doesn't work
BinaryWriter Writer = null;
string name = #"C:\Temp\yourfile.wav";
try
{
Writer = new BinaryWriter(File.OpenWrite(name));
Writer.Write(this.audioData);
Writer.Flush();
Writer.Close();
}
catch
{
...
}
But nothing work for me... What I did wrong?
Ok. Let's say I can send my data as json string to the controller:
WebClient net = new WebClient();
string data = UTF8Encoding.UTF8.GetString(this.audioData, 0, this.audioData.Length);
net.UploadStringAsync(new Uri("/Home/SaveFile", UriKind.Relative), data);
How would I get this data in MVC Action?

Silverlight is running client side, your MVC code is server-side, so this won't work in it's current guise.
I'd recommend using a web service to send the data back to your server to save it.
Take a look at using WCF or maybe WebAPI to get up and running with it.
If you really wanted to do get intricate, you could also use something like SignalR to have the client / server (which is essentially what this set up is) send communicate with each other and send the data back through that. Though it seems a little overkill for this.

Related

How I can save *.docx file in sql server and show it

I have some problem. I'am try to save *.docx fail in sql server and show it in web-site. I can save my file in sql server using this code
Byte[] bytes = File.ReadAllBytes(varFilePath);
String file = Convert.ToBase64String(bytes);
using (SqlConnection sql_connetion = new SqlConnection(ConfigurationManager.ConnectionStrings["Database_connection"].ConnectionString))
{
sql_connetion.Open();
using (var sqlWrite = new SqlCommand("INSERT INTO use_of_rule (ID, taj) Values('3', #File)", sql_connetion))
{
sqlWrite.Parameters.Add("#File", bytes);
sqlWrite.ExecuteNonQuery();
return "ok";
}
}
I want to display the content of the file in the web browser. How I can do it?
If you are using Word from WAS (Office Web App Server), you need to do something like this:
1 Create a simple web site to read the data from sql.
You could create a Generic Handler (ashx) in ASP.Net site, providing the plain word file data as response. Dont forget to set the content type as "application/vnd.openxmlformats-officedocument.wordprocessingml.document".
2 Use url encoding to encode the link created in step 1, including all parameters you may want to pass into it.
3 To launch Word, you need to nav it to http(s)://your.was.server.name/op/view.aspx?src=paste.encoded.url.here

Send image from Ios application to web api service

We have an IOS application which send images to a asp.net web api application. So we convert images to Base64 then we send it to the web service as a string .
The problem is that the size of the image is big so the conversion to base64 takes a lot of time and the size of the result string is bigger than the initial image's size.
I need to know :
If another better way , instead of conversion to Base64, exists to convert the image before calling the web service
I used Gzip to compress/decompress an array of bytes like this :
static byte[] Compress(byte[] data)
{
using (var compressedStream = new MemoryStream())
using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
{
zipStream.Write(data, 0, data.Length);
zipStream.Close();
return compressedStream.ToArray();
}
}
Is it possible to convert image to array of bytes in IOS part then call the web service ? Or expose an object like compressedStream or GZipStream as a service argument?
Thanks,
it is possible to convert the image to a byte array, here's an SO answer which touches on that : how to convert byte array to image in ios
The biggest question however is this : do you actually need the image that big? You need to consider that the service will get slow once you have multiple users doing this and will more than likely grind to a halt which will make your app difficult/ slow to use.
You might want to consider reducing the image before sending it over. You can reduce the size, the quality and just make it smaller, then send the result over the wire.
Here is another SO post which touches on this : What's the easiest way to resize/optimize an image size with the iPhone SDK?
Of course if you are using xamarin and c# to build your app then it's even easier and you can find samples of code doing both these things.

Asp.Net advanced file uploading

When using a standard <input type="file" /> on an mvc3 site, you can receive the file in your action method by creating an input parameter of type HttpPostedFile and setting the form to enctype="multipart/form-data"
One of the problems of this approach is that the request does not complete and is not handed off to your action method until the entire contents of the file have been uploaded.
I would like to do some things to that file as it is being uploaded to the server. Basically i want to asynchronously receive the data as it comes in and then programmatically handle the data byte by byte.
To accomplish the above I imagine you will need to handle this part of the request in an HttpModule or custom HttpHandler perhaps. I am familiar with how those things work, but I am not familiar with the method of receiving the file upload data asynchronously as it comes in.
I know this is possible because I have worked with 3rd party components in the past that do this (normally so they can report upload progress, or cache the data to disk to avoid iis/asp.net memory limitations). Unfortunately all the components I have used are closed source so I can't peek inside and see what they are doing.
I am not looking for code, but can someone get me pointed in the right direction here?
Using a WCF service you can send file streams to and from your service.
Here is the service side receive code I use:
int chunkSize = 2048;
byte[] buffer = new byte[chunkSize];
using (System.IO.FileStream writeStream =
new System.IO.FileStream(file.FullName, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write))
{
do
{
// read bytes from input stream
int bytesRead = request.FileByteStream.Read(buffer, 0, chunkSize);
if (bytesRead == 0) break;
// write bytes to output stream
writeStream.Write(buffer, 0, bytesRead);
} while (true);
writeStream.Close();
}
If that looks like what you want, check out the CodeProject File Transfer Progress. It goes into a lot of detail that my code is loosely based on.

webservice to return pdf with asp.net

I have a html to pdf conversion tool which resides on our server that I can access using a url with querystrings.
Something like myurl.com/createpdf.aspx?page=http://www.somesite.com.
The tool then converts the web page and displays it as a pdf.
I would like to offer this functionality as a web service, so that our clients can access this programmatically.
Ideal case would be, that our clients send in the site they would like to have converted and the web service then returns the pdf.
Would that make sense?
What would be the best way to implement this?
cheers,
Terry
Use file IO to read the PDF in and have your webmethod return it as a byte[] array. For example like this:byte[] filebytes = null;
using (FileStream fs = File.OpenRead(fileName))
{
filebytes = new byte[fs.Length];
fs.Read(filebytes, (int)0, (int)fs.Length);
}
return filebytes;
It will be Base64 encoded and you will then be able to Save and view the file on the client.
You could also write an http-handler that returns the pdf with the appropriate mime type. This way you would not have all the processing overhead of an aspx page.

Can PHP decompress a file compressed with the .NET GZipStream class?

I have a C# application that communicates with a PHP-based SOAP web service for updates and licensing.
I am now working on a feedback system for users to submit errors and tracelogs automatically through the software. Based on a previous question I posted, I felt that a web service would be the best way to do it (most likely to work properly with least configuration).
My current thought is to use .NET built-in gzip compression to compress the text file, convert to base64, send to the web-service, and have the PHP script convert to binary and uncompress the data.
Can PHP decompress data compressed with GZipStream, and if so, how?
I actually tried this. GZipStream doesn't work. On the other hand, compressing with DeflateStream on .NET side and decompressing with gzinflate on PHP side do work. Your mileage may vary...
If the http-level libraries implements it (Both client and server), http has support for gzip-compression, in which case there would be no reason to manually compress anything. You should check if this is already happening before you venture any further.
Since the server is accepting web requests you really should be checking the HTTP headers to determine if any client accepts GZIP encoding rather than just guessing and gzipping each and every time.
If the PHP client can do gzip itll set the header and your code will then react according and do the right thing. Assuming or guessing is a poor choice when the facility is provided for your code to learn the capabilities of the client.
I wrote an article I recently posted that shows how to compress/decompress in C#. I used it for almost the same scenario. I wanted to transfer log files from the client to the server and they were often quite large. However in my case my webservice was running in .NET so I could use the decompress method. But looks like PHP does support a method called gzdecode that would work.
http://coding.infoconex.com/post/2009/05/Compress-and-Decompress-using-net-framework-and-built-in-GZipStream.aspx
Yes, PHP can decompress GZIP compressed strings, with or without headers.
gzdecode for GZIP file format (ie, compatible with gzip)
gzinflate for "raw" DEFLATE format
gzuncompress for ZLIB format (GZIP format without some header info)
I don't know for sure which one you'd want as I'm unfamiliar with .NET GZipStream. It sounds a little like gzuncompress, as the ZLIB format is kind of a "streaming" format, but try all three.
I was able to demo this with Gzip on C# and PHP.
Gzip Compressing in C#:
using System;
using System.IO;
using System.IO.Compression;
using System.Text;
public class Program {
public static void Main() {
string s = "Hi!!";
byte[] byteArray = Encoding.UTF8.GetBytes(s);
byte[] b2 = Compress(byteArray);
Console.WriteLine(System.Convert.ToBase64String(b2));
}
public static byte[] Compress(byte[] bytes) {
using (var memoryStream = new MemoryStream()) {
using (var gzipStream = new GZipStream(memoryStream, CompressionLevel.Optimal)) {
gzipStream.Write(bytes, 0, bytes.Length);
}
return memoryStream.ToArray();
}
}
public static byte[] Decompress(byte[] bytes) {
using (var memoryStream = new MemoryStream(bytes)) {
using (var outputStream = new MemoryStream()) {
using (var decompressStream = new GZipStream(memoryStream, CompressionMode.Decompress)) {
decompressStream.CopyTo(outputStream);
}
return outputStream.ToArray();
}
}
}
}
the code above prints the base64 encoded compressed string which is H4sIAAAAAAAEAPPIVFQEANxaFPgEAAAA for the Hi!! input.
Here's the code to decompress in PHP:
echo gzdecode(base64_decode('H4sIAAAAAAAEAPPIVFQEANxaFPgEAAAA'));

Categories