How to pass Array values to asp.net c# web services - c#

In my client project(asp.net MVC4) I have a class file
public class Person
{
public string Name { get; set; }
public int Phone { get; set; }
}
And from the controller I try to call my web service method. The web service part is different project.
Person per = new Person();
per.Name = "Vibin";
per.Phone = 123456789;
FirstService.WebService service = new FirstService.WebService();
service.TakeList(per);
And my web service method is
[WebMethod]
public void TakeList(Person theList)
{
// stuff
}
The problem is I am unable to pass the value to the web method. I searched a lot to find a solution but failed. Please help me to fix this issue. Also please provide an example for sending array values to web service in asp.net c#. Thanks in advance.

I don't know but it is issue of type ambiguity.
You person class that you have used is not same as Web Service defined even though both has same property.
When you add web reference it will create its own entity and you have to map your MVC model to Web service model.
Person per = new Person(); // your MVC4 App local model.
per.Name = "Vibin";
per.Phone = 123456789;
FirstService.WebService service = new FirstService.WebService();
mvcEmpty.FirstService.Person p = new mvcEmpty.FirstService.Person(); // Web service person generated during proxy generation when you add web reference.
p.Name = per.Name;
p.phone = per.Phone;
service.TakeList(p);

By using (serialize and deserialize) you can do that.
Serialize the object at client side(it will sending as byte of array).
Deserialize the received byte of array to your object at web service side.
Use the below code:
// Convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
{
if(obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
// Convert a byte array to an Object
private Object ByteArrayToObject(byte[] arrBytes)
{
MemoryStream memStream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
Object obj = (Object) binForm.Deserialize(memStream);
return obj;
}

Related

getting different results from converting an object to a byte array

I am trying to create a messenger using asp.net core and WebSockets.I want the client to convert a Message object to byte[] and send it to the server by a WebSocket. But on the server-side, I can't deserialize the object that the client serialized. after some debugging, I found some differences between serialized buffers from the same objects on both sides.
actully, the serialized byte[] from msg object on the server-side is not the same as serialized byte[] from msg object on the client-side.
Here is my code on the server-side:
Message msg = new Message()
{
Text="Test"
};
var test = ObjectToByteArray(msg);
public static byte[] ObjectToByteArray(Object obj)
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
[Serializable]
public class Message
{
public string Text { get; set; }
}
And exactly the same code on the client-side (my server-side is asp.net core 5 API and my client-side is Avalonia dotnet 6)
but here is peace of var test on the server-side (note that it has 170 bytes):
and here is peace of var test on the client-side (note that it has 160 bytes):
why they are different? how I can fix this bug?

Convert Javascript Float32Array to c# FileStream sending throw SignalR

To follow my previous question:
WebRTC and Asp.NetCore
I have an Angular App which record the microphone and, using SignalR, send a Float32Array to my .Net Core Api which will save it in a wav File.
public class BaseHub : Hub
{
public void SendStream(object o)
{
float[] floatArray = (float[])o; //the conversion doesnt work
byte[] bytes = new byte[floatArray .Length * sizeof(float)];
using (FileStream fs = new FileStream("./mywavfile.wav", FileMode.Append))
{
fs.Write(bytes, 0, bytes.Length);
}
}
}
Watch result of o in Visual Studio
Content of the resultView of o
How can I convert a Float32Array from javascript to float[] in c# sending throw SignalR?
You need to parse the JObject. here is an example:
static void Main(string[] args)
{
// something like this is coming as the request
var str = "{\"0\":0.0,\"1\":0.1,\"2\":0.2,\"3\":0.3,\"4\":0.4,\"5\":0.5}";
// you are getting a JObject, this is the type of "object o",
// I am loading one here using the same schema we see in your example.
var jobj = JObject.Load(new JsonTextReader(new StringReader(str)));
// now we simply need to parse out all the values.
// Below are 3 options in order from "least amount of built in functions"
// to most built in usage.
// personally, I use option 3
// option 1:
// loop over the children as properties.
var output = new List<float>();
foreach (var prop in jobj.Children<JProperty>())
{
output.Add(float.Parse(prop.Value.ToString()));
}
// option 2:
// convert directly using linq
float [] outputAsArray = jobj.Children<JProperty>().Select(x => float.Parse(x.Value.ToString())).ToArray();
//option 3 cast and convert using Json.Net
outputAsArray = jobj.Children<JProperty>().Values<float>().ToArray();
}

Serializing Protobuf Object and Sending with ØMQ/ZMQ

I have a protobuf object that I am sending from a C# application (using clrZmq) to a C++ service (using the zmq C++ bindings) on a local machine (for testing). I attempt to send my object from C# using the following
Taurus.Odds odds = Util.GetFakeOdds();
using (var context = ZmqContext.Create())
using (var socket = context.CreateSocket(SocketType.REQ))
{
byte[] buffer = null;
socket.Connect(TARGET); // TARGET = "tcp://127.0.0.1:6500"
Taurus.FeedMux mux = new Taurus.FeedMux();
mux.type = Taurus.FeedMux.Type.ODDS;
mux.odds = odds;
SendStatus status = socket.Send(mux.ToByteArray());
if (status == SendStatus.Sent)
{
int i;
byte[] arr = socket.Receive(buffer, SocketFlags.None, out i);
Taurus.Bet bet = buffer.ToObject<Taurus.Bet>();
}
...
}
Where I am serializing to my Taurus.Odds object to byte[] via the extension method
public static byte[] ToByteArray(this object o)
{
if(o == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, o);
return ms.ToArray();
}
}
I see in my C++ application that the code receives the message, but the C++ ZMQ classes fail to de-serialize it correctly. I have some Java code that send to the C++ code in the same way without issue. My question is, am I sending my object via ZMQ correctly in the above and if not what am I doing wrong?
Thanks for your time.
Here's your error:
I am serializing to my Taurus.Odds object to byte[] via the extension method
...
BinaryFormatter bf = new BinaryFormatter();
...
You seem to be unaware of what BinaryFormatter is. It is in no way related to ProtoBuf. The docs say the following:
Serializes and deserializes an object, or an entire graph of connected objects, in binary format.
This binary format is a .NET-specific implementation detail. And it's very rigid at that, with poor versioning support. It was mainly used in the .NET remoting days, and it's generally considered a bad idea to use it today, as there are much better serializers around.
As you can see, there's no way your C++ app could be able to read that, as it's not in protobuf format.
So throw this method away and replace it with some proper protobuf serializing code, as explained in the protobuf-net docs. You'll need to add [ProtoContract] and [ProtoMember] attributes in your objects. Then you could write something like:
public static byte[] ToByteArray<T>(this T o)
{
if (o == null)
return null;
using (MemoryStream ms = new MemoryStream())
{
ProtoBuf.Serializer.Serialize(ms, o);
return ms.ToArray();
}
}

How to fix OutOfMemoryException when serializing to JSON string?

I have a Class object which contains a property as byte array in it. This class is a Data Contract to my REST service. The byte array property will take any document whose Max Size is limited to 500MB. When I was trying to consume this service and serializing the object I am getting the Memory Out of exception error. Please find the below image
Below is the code snippet
public static string SerializeJSon<T>(T t)
{
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(T));
DataContractJsonSerializerSettings s = new DataContractJsonSerializerSettings();
DateTimeFormat dt = new DateTimeFormat("MM/dd/yyyy");
s.DateTimeFormat = dt;
**ds.WriteObject(stream, t);**
string jsonString = Encoding.UTF8.GetString(stream.ToArray());
stream.Close();
return jsonString;
}
Try "do not use 500mb documents in web service calls". THs is the core problem - you try to use a method call mechanism to transport half a gigabyte of data that likely turns into some gigabyte of in memory objects. This is not what web services are designed to do.

How to serialize/deserialize a C# WCF DataContract to/from XML

I am developing a WCF service which will be consumed by multiple different client applications. In order to make one functionality work, the server needs to read an XML file into a C# DataContract which is then passed on to the concerned client. As far as I understand from the MSDN website, this is possible but I couldn't find any complete examples. In particular, the website talks about a 'stream' parameter which I don't quite get yet.
My data contract has one property field which is a list of another data contract which has multiple simple property fields.
e.g.
[DataContract]
public class MyClass1 {
[DataMember]
public string name;
[DataMember]
public int age;
}
[DataContract]
public class MyClass2 {
[DataMember]
public List<MyClass1> myClass1List;
}
My classes look something like this.
Here is an example
MyClass1 obj = new MyClass1();
DataContractSerializer dcs = new DataContractSerializer(typeof(MyClass1));
using (Stream stream = new FileStream(#"C:\tmp\file.xml", FileMode.Create, FileAccess.Write))
{
using (XmlDictionaryWriter writer =
XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8))
{
writer.WriteStartDocument();
dcs.WriteObject(writer, obj);
}
}
Books b = new Books();
DataContractSerializer dcs = new DataContractSerializer(typeof(Books));
try
{
Stream fs = new FileStream(#"C:\Users\temelm\Desktop\XmlFile.xml", FileMode.Create, FileAccess.Write);
XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateTextWriter(fs, Encoding.UTF8);
xdw.WriteStartDocument();
dcs.WriteObject(xdw, b);
xdw.Close();
fs.Flush();
fs.Close();
}
catch (Exception e)
{
s += e.Message + "\n";
}
This can be useful for you. When you need XElement. For instance when you going append node to XDocument or replece XElement of this document.
private XElement objectToXElement(SomeContractType obj)
{
DataContractSerializer dcs = new DataContractSerializer(typeof(SomeContractType);
var ms = new MemoryStream();
var xw = XmlWriter.Create(ms);
dcs.WriteObject(xw, obj);
xw.Flush();
xw.Close();
ms.Position = 0;
XElement xe = XElement.Load(ms);
return xe;
}
There is the NetDataContractSerializer which solves a whole bunch of problems when using WCF.
See here MSDN NetDataContractSerializer
It is typically used for wrapping all kinds of objects and pass it over WCF.
You can use it for wrapping objects into a byte[] and transport it over WCF,
on the serverside, you can easily Deserialize the objects and do whatever
you want with them.
Here is a discussion on how to use this Serializer correctly:
MSDN Social
Code snippets are provided there also!

Categories

Resources