How to Show a Binary Data in an Image - c#

Actually, I have saved <Binary data> in Database by :
HttpPostedFile PostedFile = Request.Files[m + 2];
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[m + 2].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[m + 2].ContentLength);
}
Now, I wanted to show the <Binary data> in an Image.
I have used a bit code like :
ASPxImage objimg = new ASPxImage();
objimg.ID = "objimg" + (j + 1);
objimg.Width = 100;
objimg.Height = 100;
byte[] buffer = null;
buffer = (byte[])DtChoices.Rows[j]["COLUMN_IMAGE"];
MemoryStream ms = new MemoryStream(buffer);
objimg.Value = System.Drawing.Image.FromStream(ms);
But, I am unable to display Image.Can anyone Help Me?

I have not used the DevExpress controls library, but from the documentation I can gather than the correct class to do this is ASPxBinaryImage. There's an example available on their website at http://www.devexpress.com/Support/Center/Example/Details/E1414
Your control -
<dxe:ASPxBinaryImage ID="ASPxBinaryImage1" runat="server" Value='<%# ConvertOleObjectToByteArray(Eval("Image")) %>'></dxe:ASPxBinaryImage>
The conversion function -
public partial class _Default : System.Web.UI.Page {
const string BITMAP_ID_BLOCK = "BM";
const string JPG_ID_BLOCK = "\u00FF\u00D8\u00FF";
const string PNG_ID_BLOCK = "\u0089PNG\r\n\u001a\n";
const string GIF_ID_BLOCK = "GIF8";
const string TIFF_ID_BLOCK = "II*\u0000";
const int DEFAULT_OLEHEADERSIZE = 78;
public static byte[] ConvertOleObjectToByteArray(object content) {
if (content != null && !(content is DBNull)) {
byte[] oleFieldBytes = (byte[])content;
byte[] imageBytes = null;
// Get a UTF7 Encoded string version
Encoding u8 = Encoding.UTF7;
string strTemp = u8.GetString(oleFieldBytes);
// Get the first 300 characters from the string
string strVTemp = strTemp.Substring(0, 300);
// Search for the block
int iPos = -1;
if (strVTemp.IndexOf(BITMAP_ID_BLOCK) != -1) {
iPos = strVTemp.IndexOf(BITMAP_ID_BLOCK);
} else if (strVTemp.IndexOf(JPG_ID_BLOCK) != -1) {
iPos = strVTemp.IndexOf(JPG_ID_BLOCK);
} else if (strVTemp.IndexOf(PNG_ID_BLOCK) != -1) {
iPos = strVTemp.IndexOf(PNG_ID_BLOCK);
} else if (strVTemp.IndexOf(GIF_ID_BLOCK) != -1) {
iPos = strVTemp.IndexOf(GIF_ID_BLOCK);
} else if (strVTemp.IndexOf(TIFF_ID_BLOCK) != -1) {
iPos = strVTemp.IndexOf(TIFF_ID_BLOCK);
}
// From the position above get the new image
if (iPos == -1) {
iPos = DEFAULT_OLEHEADERSIZE;
}
//Array.Copy(
imageBytes = new byte[oleFieldBytes.LongLength - iPos];
MemoryStream ms = new MemoryStream();
ms.Write(oleFieldBytes, iPos, oleFieldBytes.Length - iPos);
imageBytes = ms.ToArray();
ms.Close();
ms.Dispose();
return imageBytes;
}
return null;
}
}

Related

Convert a node.js script to C#

I have this function in Node.js
let inPath = process.argv[2] || 'file.txt';
let outPath = process.argv[3] || 'result.txt';
fs.open(inPath, 'r', (errIn, fdIn) => {
fs.open(outPath, 'w', (errOut, fdOut) => {
let buffer = Buffer.alloc(1);
while (true) {
let num = fs.readSync(fdIn, buffer, 0, 1, null);
if (num === 0) break;
fs.writeSync(fdOut, Buffer.from([255-buffer[0]]), 0, 1, null);
}
});
});
What would be the equivalent in C#?
My code so far. I do not know what is the equivalent code in C# to minus byte of a character. Thank you in advanced!
var inPath = "file.txt";
var outPath = "result.txt";
string result = string.Empty;
using (StreamReader file = new StreamReader(#inPath))
{
while (!file.EndOfStream)
{
string line = file.ReadLine();
foreach (char letter in line)
{
//letter = Buffer.from([255-buffer[0]]);
result += letter;
}
}
File.WriteAllText(outPath, result);
}
var inPath = "file.txt";
var outPath = "result.txt";
//Converted
using (var fdIn = new FileStream(inPath,FileMode.Open))
{
using (var fdOut = new FileStream(outPath, FileMode.OpenOrCreate))
{
var buffer = new byte[1];
var readCount = 0;
while (true)
{
readCount += fdIn.Read(buffer,0,1);
buffer[0] = (byte)(255 - buffer[0]);
fdOut.Write(buffer);
if (readCount == fdIn.Length)
break;
}
}
}
...
//Same code but all file loaded into memory, processed and after this saved
var input = File.ReadAllBytes(inPath);
for (int i = 0; i < input.Length; i++)
{
input[i] = (byte)(255 - input[i]);
}
File.WriteAllBytes(outPath, input);
Same code but with BinaryReader and BinaryWriter
var inPath = "file.txt";
var outPath = "result.txt";
using (BinaryReader fileIn = new BinaryReader(new StreamReader(#inPath).BaseStream))
using (BinaryWriter fileOut = new BinaryWriter(new StreamWriter(#outPath).BaseStream))
{
while (fileIn.BaseStream.Position != fileIn.BaseStream.Length)
{
var #byte = fileIn.ReadByte();
fileOut.Write((byte)(255 - #byte));
}
}

Extract audio from video using autogen ffmpeg C# in Unity

Hi I'm using ffmpeg autogen to extract audio from video in Unity, but when I following this code, the file write cannot write, it's 0Kb, so what's issue of this or someone have any examples for extract audio using this library, apologize for my English. This is github of library:
https://github.com/Ruslan-B/FFmpeg.AutoGen
unsafe void TestExtractAudio()
{
string inFile = Application.streamingAssetsPath + "/" + strFileName;
string outFile = Application.streamingAssetsPath + "/" + strFileNameAudio;
AVOutputFormat* outFormat = null;
AVFormatContext* inFormatContext = null;
AVFormatContext* outFormatContext = null;
AVPacket packet;
ffmpeg.av_register_all();
inFormatContext = ffmpeg.avformat_alloc_context();
outFormatContext = ffmpeg.avformat_alloc_context();
if (ffmpeg.avformat_open_input(&inFormatContext, inFile, null, null) < 0)
{
throw new ApplicationException("Could not open input file.");
}
if (ffmpeg.avformat_find_stream_info(inFormatContext, null) < 0)
{
throw new ApplicationException("Failed to retrieve input stream info.");
}
ffmpeg.avformat_alloc_output_context2(&outFormatContext, null, null, outFile);
if (outFormatContext == null)
{
throw new ApplicationException("Could not create output context");
}
outFormat = outFormatContext->oformat;
AVStream* inStream = inFormatContext->streams[1];
AVStream* outStream = ffmpeg.avformat_new_stream(outFormatContext, inStream->codec->codec);
if (outStream == null)
{
throw new ApplicationException("Failed to allocate output stream.");
}
if (ffmpeg.avcodec_copy_context(outStream->codec, inStream->codec) < 0)
{
throw new ApplicationException("Couldn't copy input stream codec context to output stream codec context");
}
outFormatContext->audio_codec_id = AVCodecID.AV_CODEC_ID_MP3;
int retcode = ffmpeg.avio_open(&outFormatContext->pb, outFile, ffmpeg.AVIO_FLAG_WRITE);
if (retcode < 0)
{
throw new ApplicationException("Couldn't open output file");
}
int returnCode = ffmpeg.avformat_write_header(outFormatContext, null);
if (returnCode < 0)
{
throw new ApplicationException("Error occurred opening output file.");
}
while (true)
{
if (ffmpeg.av_read_frame(inFormatContext, &packet) < 0)
{
break;
}
if (packet.stream_index == 1)
{
inStream = inFormatContext->streams[1];
outStream = outFormatContext->streams[0];
// TODO: Replicate log packet functionality to print out what's inside the packet.
packet.pts = ffmpeg.av_rescale_q_rnd(packet.pts, inStream->time_base, outStream->time_base,
AVRounding.AV_ROUND_NEAR_INF | AVRounding.AV_ROUND_PASS_MINMAX);
packet.dts = ffmpeg.av_rescale_q_rnd(packet.dts, inStream->time_base, outStream->time_base,
AVRounding.AV_ROUND_NEAR_INF | AVRounding.AV_ROUND_PASS_MINMAX);
packet.duration = ffmpeg.av_rescale_q(packet.duration, inStream->time_base, outStream->time_base);
int returncode = ffmpeg.av_interleaved_write_frame(outFormatContext, &packet);
}
ffmpeg.av_packet_unref(&packet);
}
ffmpeg.av_write_trailer(outFormatContext);
ffmpeg.avformat_close_input(&inFormatContext);
ffmpeg.avformat_free_context(outFormatContext);
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
the value returnCode return less than 0, so someone can fix this, thanks so much for that
The problem is here:
inStream = inFormatContext->streams[1];
outStream = outFormatContext->streams[0];
This code:
ffmpeg.av_interleaved_write_frame
does the following validation
static int check_packet(AVFormatContext *s, AVPacket *pkt)
{
if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n"
}
you need to change the packet.stream_index from 1 to 0 before calling
int returncode = ffmpeg.av_interleaved_write_frame(outFormatContext, &packet);
See:
if (type == AVMediaType.AVMEDIA_TYPE_AUDIO){
inStream = inFormatContext->streams[1];
outStream = outFormatContext->streams[0];
// TODO: Replicate log packet functionality to print out what's inside the packet.
ffmpeg.av_packet_rescale_ts(&packet, inStream->time_base, outStream->time_base);
packet.stream_index = 0;
int returncode = ffmpeg.av_write_frame(outFormatContext, &packet);
}

c# push notification is not working with Turkish character

I want to send notification to IOS from c#. But it does not send message contain Turkish character.
Here is my Pushmessage Function :
public bool PushMessage(string Mess, string DeviceToken, int Badge, string Custom_Field)
{
ConnectToAPNS();
List<string> Key_Value_Custom_Field = new List<string>();
String cToken = DeviceToken;
String cAlert = Mess;
int iBadge = Badge;
// Ready to create the push notification
byte[] buf = new byte[256];
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
bw.Write(new byte[] { 0, 0, 32 });
byte[] deviceToken = HexToData(cToken);
bw.Write(deviceToken);
bw.Write((byte)0);
// Create the APNS payload - new.caf is an audio file saved in the application bundle on the device
string msg = "";
msg = "{\"aps\":{\"alert\":\"" + cAlert + "\",\"badge\":\"" + iBadge.ToString() + "\",\"sound\":\"noti.aiff\",\"priority\":\"10\"}";
String PayloadMess = "";
if (string.IsNullOrWhiteSpace(Custom_Field) == false)
{
List<string> list_Custom_Field = Custom_Field.Split(';').ToList();
if (list_Custom_Field.Count > 0)
{
for (int indx = 0; indx < list_Custom_Field.Count; indx++)
{
Key_Value_Custom_Field = list_Custom_Field[indx].Split('=').ToList();
if (Key_Value_Custom_Field.Count > 1)
{
if (PayloadMess != "") PayloadMess += ", ";
PayloadMess += "\"" + Key_Value_Custom_Field[0].ToString() + "\":\"" + Key_Value_Custom_Field[1].ToString() + "\"";
}
}
}
}
if (PayloadMess != "")
{
msg += ", " + PayloadMess;
}
msg += "}";
bw.Write((byte)0);
bw.Write((byte)msg.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(msg);
bw.Write(b1);
bw.Flush();
if (sslStream != null)
{
sslStream.Write(ms.ToArray());
return true;
}
return false;
}
Here is the solution:
I change
bw.Write((byte)msg.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(msg);
bw.Write(b1);
to
byte[] bytes = Encoding.UTF8.GetBytes(msg);
// Write the data out to the stream
bw.Write((byte)bytes.Length);
bw.Write(msg.ToCharArray());
Now it works.The problem is character count was wrong.
Probably you just used
Encoding.UTF8.GetBytes(Message);
You can try the following:
Encoding iso = Encoding.GetEncoding("ISO-8859-9"); //Turkish
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
string msg = iso.GetString(isoBytes);

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);

How to uploadfile using WCF 4.0 Template (REST)

How to upload file (500 MB size and up...) in Restful webservice then save the file in specific location?
If you have links, please share.
I use Fiddler to test the service.
Here are codes that I've been working for.
[WebInvoke(UriTemplate = "Add", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public bool UploadFile(FileUploader.File userFile, System.IO.Stream fileStream)
{
FileUploader.Logic.StreamObject streamUploader = new FileUploader.Logic.StreamObject();
streamUploader.UploadFile(userFile.FileName, fileStream);
return true;
}
public class StreamObject : IStreamObject
{
public void UploadFile(string filename, Stream fileStream)
{
byte[] buffer = new byte[10000];
int bytesRead, totalbytesRead = 0;
do
{
bytesRead = fileStream.Read(buffer, 0, buffer.Length);
totalbytesRead += bytesRead;
} while (bytesRead > 0);
}
}
An example on how to upload a file to a REST service is shown below:
private byte[] UseWebClientForFileUpload(string serviceBaseUrl, String resourceUrl, string filePath)
{
var c = new WebClient();
c.OpenWrite(string.Concat(serviceBaseUrl, resourceUrl), "POST");
c.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
return c.UploadFile(string.Concat(serviceBaseUrl, resourceUrl), filePath);
}
Make sure to set appropriate content type. I think we cannot pass multiple parameters when using Stream as one of the params, so in order to get the filename and the stream just pass everything as a single stream and then use a parser that would seperate your stream. There is something called a multipartParser as shown below:
public class MultipartParser
{
public MultipartParser(Stream stream)
{
this.Parse(stream, Encoding.UTF8);
ParseParameter(stream, Encoding.UTF8);
}
public MultipartParser(Stream stream, Encoding encoding)
{
this.Parse(stream, encoding);
}
private void Parse(Stream stream, Encoding encoding)
{
this.Success = false;
// Read the stream into a byte array
byte[] data = ToByteArray(stream);
// Copy to a string for header parsing
string content = encoding.GetString(data);
// The first line should contain the delimiter
int delimiterEndIndex = content.IndexOf("\r\n");
if (delimiterEndIndex > -1)
{
string delimiter = content.Substring(0, content.IndexOf("\r\n"));
// Look for Content-Type
Regex re = new Regex(#"(?<=Content\-Type:)(.*?)(?=\r\n\r\n)");
Match contentTypeMatch = re.Match(content);
// Look for filename
re = new Regex(#"(?<=filename\=\"")(.*?)(?=\"")");
Match filenameMatch = re.Match(content);
// Did we find the required values?
if (contentTypeMatch.Success && filenameMatch.Success)
{
// Set properties
this.ContentType = contentTypeMatch.Value.Trim();
this.Filename = filenameMatch.Value.Trim();
// Get the start & end indexes of the file contents
int startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;
byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
int endIndex = IndexOf(data, delimiterBytes, startIndex);
int contentLength = endIndex - startIndex;
// Extract the file contents from the byte array
byte[] fileData = new byte[contentLength];
Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength);
this.FileContents = fileData;
this.Success = true;
}
}
}
private void ParseParameter(Stream stream, Encoding encoding)
{
this.Success = false;
// Read the stream into a byte array
byte[] data = ToByteArray(stream);
// Copy to a string for header parsing
string content = encoding.GetString(data);
// The first line should contain the delimiter
int delimiterEndIndex = content.IndexOf("\r\n");
if (delimiterEndIndex > -1)
{
string delimiter = content.Substring(0, content.IndexOf("\r\n"));
string[] splitContents = content.Split(new[] {delimiter}, StringSplitOptions.RemoveEmptyEntries);
foreach (string t in splitContents)
{
// Look for Content-Type
Regex contentTypeRegex = new Regex(#"(?<=Content\-Type:)(.*?)(?=\r\n\r\n)");
Match contentTypeMatch = contentTypeRegex.Match(t);
// Look for name of parameter
Regex re = new Regex(#"(?<=name\=\"")(.*)");
Match name = re.Match(t);
// Look for filename
re = new Regex(#"(?<=filename\=\"")(.*?)(?=\"")");
Match filenameMatch = re.Match(t);
// Did we find the required values?
if (name.Success || filenameMatch.Success)
{
// Set properties
//this.ContentType = name.Value.Trim();
int startIndex;
if (filenameMatch.Success)
{
this.Filename = filenameMatch.Value.Trim();
}
if(contentTypeMatch.Success)
{
// Get the start & end indexes of the file contents
startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;
}
else
{
startIndex = name.Index + name.Length + "\r\n\r\n".Length;
}
//byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
//int endIndex = IndexOf(data, delimiterBytes, startIndex);
//int contentLength = t.Length - startIndex;
string propertyData = t.Substring(startIndex - 1, t.Length - startIndex);
// Extract the file contents from the byte array
//byte[] paramData = new byte[contentLength];
//Buffer.BlockCopy(data, startIndex, paramData, 0, contentLength);
MyContent myContent = new MyContent();
myContent.Data = encoding.GetBytes(propertyData);
myContent.StringData = propertyData;
myContent.PropertyName = name.Value.Trim();
if (MyContents == null)
MyContents = new List<MyContent>();
MyContents.Add(myContent);
this.Success = true;
}
}
}
}
private int IndexOf(byte[] searchWithin, byte[] serachFor, int startIndex)
{
int index = 0;
int startPos = Array.IndexOf(searchWithin, serachFor[0], startIndex);
if (startPos != -1)
{
while ((startPos + index) < searchWithin.Length)
{
if (searchWithin[startPos + index] == serachFor[index])
{
index++;
if (index == serachFor.Length)
{
return startPos;
}
}
else
{
startPos = Array.IndexOf<byte>(searchWithin, serachFor[0], startPos + index);
if (startPos == -1)
{
return -1;
}
index = 0;
}
}
}
return -1;
}
private byte[] ToByteArray(Stream stream)
{
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public List<MyContent> MyContents { get; set; }
public bool Success
{
get;
private set;
}
public string ContentType
{
get;
private set;
}
public string Filename
{
get;
private set;
}
public byte[] FileContents
{
get;
private set;
}
}
public class MyContent
{
public byte[] Data { get; set; }
public string PropertyName { get; set; }
public string StringData { get; set; }
}
I did get the multipartParser from a here
The answer stems from what I have done before. The service may look as follows:
[ServiceContract]
public class DocumentService
{
[OperationContract]
[WebTemplate("{name}"]
public Document Create(Stream stream, string name)
{
var id = Guid.NewGuid().ToString("N");
using(FileStream outputStream = File.Create(Path.Combine("c:\\temp\\", id)))
{
stream.CopyTo(outputStream);
}
Document document = new Document();
document.Name = name;
document.Id = id;
// Save document to database
// Set headers
return document;
}
}
where Document may look as follows:
[DataContract]
public class Document
{
[DataMember]
public string Id
{
get;set;
}
[DataMember]
public string Name
{
get;set;
}
/* other fields */
}
To upload a file to the service (assuming it is at http://api.example.com/documents/), you can do the following:
string name = "mydocument.doc";
var request = WebRequest.Create ("http://api.example.com/documents/" + name);
request.ContentType = "application/octet-stream";
request.Method = "POST";
using(var stream = request.GetRequestStream())
{
using(var inputStream = File.OpenRead("c:\\mydocument.doc"))
{
inputStream.CopyTo(stream);
}
}
using(var response = (HttpWebResponse)request.GetResponse())
{
// process the response, if needed
}
There is no need to send a multipart stream over if all you do is sending one stream. It is important that any parameters (such as name) should be part of the UriTemplate.

Categories

Resources