How to pass through the soap memory stream? - c#

I create memory stream.
var memoryStream = new MemoryStream();
var binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, list.ToArray());
And I need to pass through the soap to java server and insert to database.
And how create webService method ?
#WebMethod(operationName = "CreateObject")
public String CreateTopology(
#WebParam(name = "session")int id_session,
#WebParam(name = "title") String title,
#WebParam(name = "content") Object content,
#WebParam(name = "access") Integer access) {
EDIT:
Problem. I have serialized object in C #. I need to pass it on to the server via SOAP Java, after that save it in MySQL database in field of type Blob (may not be the blob)

Have a look here:
//build a Call object
Call call = new Call();
call.setTargetObjectURI("urn:greetingService");
call.setMethodName("sayGreeting");
call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
//creating a parameter list
Vector params = new Vector();
params.addElement(new Parameter("name", String.class, name,null));
//adding the parameter(s) to the Call object
call.setParams(params);
You are setting the method-name "sayGreeting" and in a vector params you specify the parameters which the method will be called with. This parameter-vector is what you need!
The code-sample is taken from page 2 of this tutorial which i very much recommend: http://javaboutique.internet.com/tutorials/SOAP/

base64String - to pass as string
var memoryStream = new MemoryStream();
var binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, m_workspace.ListPlatforms.ToArray());
String base64String = Convert.ToBase64String(memoryStream.ToArray());

Related

Retrieving only half the Image when converting to Base64

I have an API which reads an uploaded Image and changes it to a byte[], however in the database the field for where I have to save the image is a string instead of varbinary(MAX), and I cannot change the field type of the database.
I thought about converting the image to base64 and then storing it but this might cause unnecessary strain on the database.
I have found online the following way but this method can be inconsistent based on the server as the encoding might change:
var str = System.Text.Encoding.Default.GetString(result);
And if I were to use the above method I would need to know what type of encoding does ReadBytes use.
Below is my code:
byte[] fileData = null;
using (var binaryReader = new BinaryReader(image.InputStream))
{
binaryReader.BaseStream.Position = 0;
fileData = binaryReader.ReadBytes(image.ContentLength);
}
Furthermore, when I converted the image to a base64 and viewed it, only half the image was visible:
var base64String = Convert.ToBase64String(fileData);
use Convert.toBase64String() method or just using MemoryStream class->
// 1.toBase64String()
string str = Convert.ToBase64String(bytes);
// 2.MemoryStream class
using (MemoryStream stream = new MemoryStream(bytes))
using (StreamReader streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
Initialize the BinaryReader with this overload that specifies the encoding.
var binaryReader = new BinaryReader(System.IO.Stream input, System.Text.Encoding encoding);

Unable to pass MemoryStream parameter to WCF method?

I have a method in Service1.svc.cs, below is the code
public void SaveData(int UserId, System.IO.MemoryStream File)
{
//Some code
}
I am passing values from xaml.cs
savedata.SaveDataAsync(userId, ms);
The error is
cannot convert from 'System.IO.MemoryStream' to
'SignSilverlight.ServiceReference1.MemoryStream'
How to solve ?
Memory stream is a .NET local object and it is not possible to pass it to a remote machine that might not even run .NET.
You have to pass a byte[] array instead. But be aware of size limits in endpoint's settings.
Here is how to (de)serialize a memory stream to array
// first endpoint
var streamSending = new MemoryStream();
var array = streamSending.ToArray();
// second endpoint
var streamRecieving = new MemoryStream(array);

reading a web api blob into a string that I can send as part of a json object to the server and turn back into a file

i'm trying to turn a wav file into a string I can send to the server as a part of a json object, so that on the server I can turn that string back into a file.
i have tried to use readAsBinaryString and read as text, can't get past error in reading the string into a byte array.
reader.onloadend = saveMedia;
reader.readAsText(Blob);
//reader.readAsBinaryString(Blob); also tried.
then the callback sends an ajax request with an object holding the string in "reader.result" and on the server i tried things like:
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] BinaryData = encoding.GetBytes(stringFromRequest);
the answers to this question below seem to be that this should not be done. but i really want to do it this way because of another tool I am using (breeze js). don't want to use a separate post action with a file data type.
releted:
File API - Blob to JSON
Found a way that works:
var reader = new FileReader();
reader.onloadend = afterRead;
reader.readAsBinaryString(blob);
function afterRead() {
// convert binary string to base64 for a safe transfer to the server.
entity.BinaryProp = window.btoa(reader.result);
}
on the server-side:
string BinaryString = (string)entityInfo.UnmappedValuesMap["BinaryProp"];
byte[] BinaryData = Convert.FromBase64String(BinaryString);
You can use fileReader.readAsDataURL(fileObject), this encode blob to base64, which can safely upload to server by API.
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
let thumbnail = reader.result;
console.log(thumbnail)
//send to API
};
The answer above is great, but there is a simpler way.
var reader = new FileReader();
reader.onloadend = afterRead;
reader.readAsDataURL(blob); // Use this function instead
function afterRead() {
entity.BinaryProp = reader.result; //result is already a base64 string!
}
See documentation here: FileReader.readAsDataURL()

Getting Json Output from Byte Array

I just started a new project on WCF and to be honest I'm very new at this with limited knowledge.
So what I'm trying to do is open a file that is stored in my computer (e.g. word, pdf, etc.) and display the contents in the webpage in JSon format. I converted the file in a byte array and tried to display the Stream. When I did that it asked me to open the file or save it. I don't want that - I just want the contents of the file to be displayed on my local host when i call the method.
Here's what I have:
public string GetRawFile()
{
string file = #"C:\.....\TestFile.pdf";
byte[] rawFile = File.ReadAllBytes(file);
//Stream stream = new MemoryStream(rawFile);
//DataContractJsonSerializer obj = newDataContractJsonSerializer(typeof(string));
//string result = obj.ReadObject(stream).ToString();
//Deserializing
MemoryStream stream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
stream.Write(rawFile, 0, rawFile.Length);
stream.Seek(0, SeekOrigin.Begin);
Object obj = (Object) binForm.Deserialize(stream);
System.Web.Script.Serialization.JavaScriptSerializer xyz = new System.Web.Script.Serialization.JavaScriptSerializer();
string ejson = xyz.Serialize(obj);
WebOperationContext.Current.OutgoingRequest.ContentType = "text/json";
return ejson;
}
I'm trying to return a string and it's not working, but when I return just the stream it's popping up the "openwith" message.
Also should I use the GET or POST on my datacontract. I'm using REST in C#.
I'm assuming that your file actually contains json. If that is the case just do this;
string file = File.ReadAllText("C:\path\to\file.extension");
You're making the problem a lot more complicated than it needs to be. Just read the file and return it's data as a string. I think you want to use GET for the http method. Generally speaking, you all use post if you're adding new content. If for example the users request would cause the application to write some data to a file or data base then you would typically use POST for the http method. If they're just requesting data, you almost always use GET.

Getting error deserializing with DataContractSerializer

When I am deserializing my object back to it's original type my object is always null.
Here is my code:
ProjectSetup obj = new ProjectSetup();
if (System.Web.HttpContext.Current.Session["ProjectSetup"] == null)
setBookProjectSetup();
string toDeserialise = System.Web.HttpContext.Current.
Session["ProjectSetup"].ToString();
DataContractSerializer dcs = new DataContractSerializer(typeof(ProjectSetup));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(toDeserialise));
obj = (ProjectSetup) dcs.ReadObject(ms, true);
return obj;
I'm going to assume that the call to setBookProjectSetup places an instance of ProjectSetup in the HttpSessionState with a key of ProjectSetup.
The issue here starts with this:
string toDeserialise = System.Web.HttpContext.Current.
Session["ProjectSetup"].ToString();
You subsequently use the contents of the toDeserialize string as the source of the deserialization.
Unless you've overloaded ToString to return a byte stream that the DataContractSerializer would be able to deserialize (it's highly unlikely) chances are you are using the implementation of ToString on Object, which will just return the type's name.
Then, you are trying to deserialize that string into your object, which isn't going to work.
What you need to do is properly serialize your object into a byte array/MemoryStream, like so:
using (var ms = new MemoryStream())
{
// Create the serializer.
var dcs = new DataContractSerializer(typeof(ProjectSetup));
// Serialize to the stream.
dcs.WriteObject(ms, System.Web.HttpContext.Current.Session["ProjectSetup"]);
At this point, the MemoryStream will be populated with a series of bytes representing your serialized object. You can then get the object back using the same MemoryStream:
// Reset the position of the stream so the read occurs in the right place.
ms.Position = 0;
// Read the object.
var obj = (ProjectSetup) dcs.ReadObject(ms);
}

Categories