I have created Web API Services.
What I am trying to do is to call that API function, namely SaveSession(string data), from code behind button click, and to pass the entire form collection data as parameter in string format.
When I call the api's uri through webclient.uploadstring(url,string);
It is calling the web service but the parameter is not getting passed.
Pls help.
Instead of using a controller action method that accepts a string, you can instead read the form-url-encoded content posted to the controller.
In the example below, the SessionController exposes a SaveSession() method that accepts a POST of form-url-encoded content and then reads the session data as a collection of KeyValuePair instances.
The example client builds a list of key-value pairs and then uses a HttpClient instance to post the FormUrlEncodedContent to the web API controller method.
Example SessionController:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace MvcApplication1.Controllers
{
public class SessionController : ApiController
{
/// <summary>
/// Saves specified the session data.
/// </summary>
/// <returns>
/// A <see cref="HttpResponseMessage"/> that represents the response to the requested operation.
/// </returns>
[HttpPost()]
public HttpResponseMessage SaveSession()
{
// Ensure content is form-url-encoded
if(!IsFormUrlEncodedContent(this.Request.Content))
{
return this.Request.CreateResponse(HttpStatusCode.BadRequest);
}
// Read content as a collection of key value pairs
foreach (var parameter in ReadAsFormUrlEncodedContentAsync(this.Request.Content).Result)
{
var key = parameter.Key;
var value = parameter.Value;
if(!String.IsNullOrEmpty(key))
{
// Do some work to persist session data here
}
}
return this.Request.CreateResponse(HttpStatusCode.OK);
}
/// <summary>
/// Determines whether the specified content is form URL encoded content.
/// </summary>
/// <param name="content">
/// The type that the <see cref="IsFormUrlEncodedContent(HttpContent)"/> method operates on.
/// </param>
/// <returns>
/// <see langword="true"/> if the specified content is form URL encoded content; otherwise, <see langword="false"/>.
/// </returns>
public static bool IsFormUrlEncodedContent(HttpContent content)
{
if (content == null || content.Headers == null)
{
return false;
}
return String.Equals(
content.Headers.ContentType.MediaType,
FormUrlEncodedMediaTypeFormatter.DefaultMediaType.MediaType,
StringComparison.OrdinalIgnoreCase
);
}
/// <summary>
/// Write the HTTP content to a collection of name/value pairs as an asynchronous operation.
/// </summary>
/// <param name="content">
/// The type that the <see cref="ReadAsFormUrlEncodedContentAsync(HttpContent)"/> method operates on.
/// </param>
/// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns>
/// <remarks>
/// The <see cref="ReadAsFormUrlEncodedContentAsync(HttpContent, CancellationToken)"/> method
/// uses the <see cref="Encoding.UTF8"/> format (or the character encoding of the document, if specified)
/// to parse the content. URL-encoded characters are decoded and multiple occurrences of the same form
/// parameter are listed as a single entry with a comma separating each value.
/// </remarks>
public static Task<IEnumerable<KeyValuePair<string, string>>> ReadAsFormUrlEncodedContentAsync(HttpContent content)
{
return ReadAsFormUrlEncodedContentAsync(content, CancellationToken.None);
}
/// <summary>
/// Write the HTTP content to a collection of name/value pairs as an asynchronous operation.
/// </summary>
/// <param name="content">
/// The type that the <see cref="ReadAsFormUrlEncodedContentAsync(HttpContent, CancellationToken)"/> method operates on.
/// </param>
/// <param name="cancellationToken">
/// The cancellation token used to propagate notification that the operation should be canceled.
/// </param>
/// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns>
/// <remarks>
/// The <see cref="ReadAsFormUrlEncodedContentAsync(HttpContent, CancellationToken)"/> method
/// uses the <see cref="Encoding.UTF8"/> format (or the character encoding of the document, if specified)
/// to parse the content. URL-encoded characters are decoded and multiple occurrences of the same form
/// parameter are listed as a single entry with a comma separating each value.
/// </remarks>
public static Task<IEnumerable<KeyValuePair<string, string>>> ReadAsFormUrlEncodedContentAsync(HttpContent content, CancellationToken cancellationToken)
{
return Task.Factory.StartNew<IEnumerable<KeyValuePair<string, string>>>(
(object state) =>
{
var result = new List<KeyValuePair<string, string>>();
var httpContent = state as HttpContent;
if (httpContent != null)
{
var encoding = Encoding.UTF8;
var charSet = httpContent.Headers.ContentType.CharSet;
if (!String.IsNullOrEmpty(charSet))
{
try
{
encoding = Encoding.GetEncoding(charSet);
}
catch (ArgumentException)
{
encoding = Encoding.UTF8;
}
}
NameValueCollection parameters = null;
using (var reader = new StreamReader(httpContent.ReadAsStreamAsync().Result, encoding))
{
parameters = HttpUtility.ParseQueryString(reader.ReadToEnd(), encoding);
}
if (parameters != null)
{
foreach(var key in parameters.AllKeys)
{
result.Add(
new KeyValuePair<string, string>(key, parameters[key])
);
}
}
}
return result;
},
content,
cancellationToken
);
}
}
}
Example Calling Client:
using System;
using System.Collections.Generic;
using System.Net.Http;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (var client = new HttpClient())
{
// Initialize HTTP client
client.BaseAddress = new Uri("http://localhost:26242/api/", UriKind.Absolute);
client.Timeout = TimeSpan.FromSeconds(10);
// Build session data to send
var values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("Item1", "Value1"));
values.Add(new KeyValuePair<string, string>("Item2", "Value2"));
values.Add(new KeyValuePair<string, string>("Item3", "Value3"));
// Send session data via POST using form-url-encoded content
using (var content = new FormUrlEncodedContent(values))
{
using (var response = client.PostAsync("session", content).Result)
{
Console.WriteLine(response.StatusCode);
}
}
}
}
}
}
I typically have the IsFormUrlEncodedContent and ReadAsFormUrlEncodedContentAsync methods as extension methods on HttpContent but placed them in the controller for the purpose of this example.
Related
I have heard that Json.NET is faster than DataContractJsonSerializer, and wanted to give it a try...
But I couldn't find any methods on JsonConvert that take a stream rather than a string.
For deserializing a file containing JSON on WinPhone, for example, I use the following code to read the file contents into a string, and then deserialize into JSON. It appears to be about 4 times slower in my (very ad-hoc) testing than using DataContractJsonSerializer to deserialize straight from the stream...
// DCJS
DataContractJsonSerializer dc = new DataContractJsonSerializer(typeof(Constants));
Constants constants = (Constants)dc.ReadObject(stream);
// JSON.NET
string json = new StreamReader(stream).ReadToEnd();
Constants constants = JsonConvert.DeserializeObject<Constants>(json);
Am I doing it wrong?
The current version of Json.net does not allow you to use the accepted answer code. A current alternative is:
public static object DeserializeFromStream(Stream stream)
{
var serializer = new JsonSerializer();
using (var sr = new StreamReader(stream))
using (var jsonTextReader = new JsonTextReader(sr))
{
return serializer.Deserialize(jsonTextReader);
}
}
Documentation: Deserialize JSON from a file stream
public static void Serialize(object value, Stream s)
{
using (StreamWriter writer = new StreamWriter(s))
using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
{
JsonSerializer ser = new JsonSerializer();
ser.Serialize(jsonWriter, value);
jsonWriter.Flush();
}
}
public static T Deserialize<T>(Stream s)
{
using (StreamReader reader = new StreamReader(s))
using (JsonTextReader jsonReader = new JsonTextReader(reader))
{
JsonSerializer ser = new JsonSerializer();
return ser.Deserialize<T>(jsonReader);
}
}
UPDATE: This no longer works in the current version, see below for correct answer (no need to vote down, this is correct on older versions).
Use the JsonTextReader class with a StreamReader or use the JsonSerializer overload that takes a StreamReader directly:
var serializer = new JsonSerializer();
serializer.Deserialize(streamReader);
I've written an extension class to help me deserializing from JSON sources (string, stream, file).
public static class JsonHelpers
{
public static T CreateFromJsonStream<T>(this Stream stream)
{
JsonSerializer serializer = new JsonSerializer();
T data;
using (StreamReader streamReader = new StreamReader(stream))
{
data = (T)serializer.Deserialize(streamReader, typeof(T));
}
return data;
}
public static T CreateFromJsonString<T>(this String json)
{
T data;
using (MemoryStream stream = new MemoryStream(System.Text.Encoding.Default.GetBytes(json)))
{
data = CreateFromJsonStream<T>(stream);
}
return data;
}
public static T CreateFromJsonFile<T>(this String fileName)
{
T data;
using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
{
data = CreateFromJsonStream<T>(fileStream);
}
return data;
}
}
Deserializing is now as easy as writing:
MyType obj1 = aStream.CreateFromJsonStream<MyType>();
MyType obj2 = "{\"key\":\"value\"}".CreateFromJsonString<MyType>();
MyType obj3 = "data.json".CreateFromJsonFile<MyType>();
Hope it will help someone else.
I arrived at this question looking for a way to stream an open ended list of objects onto a System.IO.Stream and read them off the other end, without buffering the entire list before sending. (Specifically I'm streaming persisted objects from MongoDB over Web API.)
#Paul Tyng and #Rivers did an excellent job answering the original question, and I used their answers to build a proof of concept for my problem. I decided to post my test console app here in case anyone else is facing the same issue.
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace TestJsonStream {
class Program {
static void Main(string[] args) {
using(var writeStream = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.None)) {
string pipeHandle = writeStream.GetClientHandleAsString();
var writeTask = Task.Run(() => {
using(var sw = new StreamWriter(writeStream))
using(var writer = new JsonTextWriter(sw)) {
var ser = new JsonSerializer();
writer.WriteStartArray();
for(int i = 0; i < 25; i++) {
ser.Serialize(writer, new DataItem { Item = i });
writer.Flush();
Thread.Sleep(500);
}
writer.WriteEnd();
writer.Flush();
}
});
var readTask = Task.Run(() => {
var sw = new Stopwatch();
sw.Start();
using(var readStream = new AnonymousPipeClientStream(pipeHandle))
using(var sr = new StreamReader(readStream))
using(var reader = new JsonTextReader(sr)) {
var ser = new JsonSerializer();
if(!reader.Read() || reader.TokenType != JsonToken.StartArray) {
throw new Exception("Expected start of array");
}
while(reader.Read()) {
if(reader.TokenType == JsonToken.EndArray) break;
var item = ser.Deserialize<DataItem>(reader);
Console.WriteLine("[{0}] Received item: {1}", sw.Elapsed, item);
}
}
});
Task.WaitAll(writeTask, readTask);
writeStream.DisposeLocalCopyOfClientHandle();
}
}
class DataItem {
public int Item { get; set; }
public override string ToString() {
return string.Format("{{ Item = {0} }}", Item);
}
}
}
}
Note that you may receive an exception when the AnonymousPipeServerStream is disposed, I ignored this as it isn't relevant to the problem at hand.
another option that is handy when you are running out of memory is to periodically flush
/// <summary>serialize the value in the stream.</summary>
/// <typeparam name="T">the type to serialize</typeparam>
/// <param name="stream">The stream.</param>
/// <param name="value">The value.</param>
/// <param name="settings">The json settings to use.</param>
/// <param name="bufferSize"></param>
/// <param name="leaveOpen"></param>
public static void JsonSerialize<T>(this Stream stream,[DisallowNull] T value, [DisallowNull] JsonSerializerSettings settings, int bufferSize=1024, bool leaveOpen=false)
{
using (var writer = new StreamWriter(stream,encoding: System.Text.Encoding.UTF32,bufferSize,leaveOpen))
using (var jsonWriter = new JsonTextWriter(writer))
{
var ser = JsonSerializer.Create( settings );
ser.Serialize(jsonWriter, value);
jsonWriter.Flush();
}
}
/// <summary>serialize the value in the stream asynchronously.</summary>
/// <typeparam name="T"></typeparam>
/// <param name="stream">The stream.</param>
/// <param name="value">The value.</param>
/// <param name="settings">The settings.</param>
/// <param name="bufferSize">The buffer size, in bytes, set -1 to not flush till done</param>
/// <param name="leaveOpen"> true to leave the stream open </param>
/// <param name="cancellationToken">Propagates notification that operations should be canceled.</param>
public static Task JsonSerializeAsync<T>(this Stream stream,[DisallowNull] T value, [DisallowNull] JsonSerializerSettings settings, int bufferSize=1024, bool leaveOpen=false, CancellationToken cancellationToken=default)
{
using (var writer = new StreamWriter(stream,encoding: System.Text.Encoding.UTF32,bufferSize: bufferSize,leaveOpen: leaveOpen))
using (var jsonWriter = new JsonTextWriter(writer))
{
var ser = JsonSerializer.Create( settings );
ser.Serialize(jsonWriter, value);
return jsonWriter.Flush();
}
//jsonWriter.FlushAsnc with my version gives an error on the stream
return Task.CompletedTask;
}
You can test/ use it like so:
[TestMethod()]
public void WriteFileIntoJsonTest()
{
var file = new FileInfo(Path.GetTempFileName());
try
{
var list = new HashSet<Guid>();
for (int i = 0; i < 100; i++)
{
list.Add(Guid.NewGuid());
}
file.JsonSerialize(list);
var sr = file.IsValidJson<List<Guid>>(out var result);
Assert.IsTrue(sr);
Assert.AreEqual<int>(list.Count, result.Count);
foreach (var item in result)
{
Assert.IsFalse(list.Add(item), $"The GUID {item} should already exist in the hash set");
}
}
finally
{
file.Refresh();
file.Delete();
}
}
you'd need to create the extension methods, here is the whole set:
public static class JsonStreamReaderExt
{
static JsonSerializerSettings _settings ;
static JsonStreamReaderExt()
{
_settings = JsonConvert.DefaultSettings?.Invoke() ?? new JsonSerializerSettings();
_settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
_settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
_settings.DateFormatHandling = DateFormatHandling.IsoDateFormat ;
}
/// <summary>
/// serialize the value in the stream.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="stream">The stream.</param>
/// <param name="value">The value.</param>
public static void JsonSerialize<T>(this Stream stream,[DisallowNull] T value)
{
stream.JsonSerialize(value,_settings);
}
/// <summary>
/// serialize the value in the file .
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="file">The file.</param>
/// <param name="value">The value.</param>
public static void JsonSerialize<T>(this FileInfo file,[DisallowNull] T value)
{
if (string.IsNullOrEmpty(file.DirectoryName)==true && Directory.Exists(file.DirectoryName) == false)
{
Directory.CreateDirectory(file.FullName);
}
using var s = file.OpenWrite();
s.JsonSerialize(value, _settings);
file.Refresh();
}
/// <summary>
/// serialize the value in the file .
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="file">The file.</param>
/// <param name="value">The value.</param>
/// <param name="settings">the json settings to use</param>
public static void JsonSerialize<T>(this FileInfo file, [DisallowNull] T value, [DisallowNull] JsonSerializerSettings settings)
{
if (string.IsNullOrEmpty(file.DirectoryName) == true && Directory.Exists(file.DirectoryName) == false)
{
Directory.CreateDirectory(file.FullName);
}
using var s = file.OpenWrite();
s.JsonSerialize(value, settings);
file.Refresh();
}
/// <summary>
/// serialize the value in the file .
/// </summary>
/// <remarks>File will be refreshed to contain the new meta data</remarks>
/// <typeparam name="T">the type to serialize</typeparam>
/// <param name="file">The file.</param>
/// <param name="value">The value.</param>
/// <param name="cancellationToken">Propagates notification that operations should be canceled.</param>
public static async Task JsonSerializeAsync<T>(this FileInfo file, [DisallowNull] T value, CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(file.DirectoryName) == true && Directory.Exists(file.DirectoryName) == false)
{
Directory.CreateDirectory(file.FullName);
}
using (var stream = file.OpenWrite())
{
await stream.JsonSerializeAsync(value, _settings,bufferSize:1024,leaveOpen:false, cancellationToken).ConfigureAwait(false);
}
file.Refresh();
}
/// <summary>
/// serialize the value in the file .
/// </summary>
/// <remarks>File will be refreshed to contain the new meta data</remarks>
/// <typeparam name="T">the type to serialize</typeparam>
/// <param name="file">The file to create or overwrite.</param>
/// <param name="value">The value.</param>
/// <param name="settings">the json settings to use</param>
/// <param name="cancellationToken">Propagates notification that operations should be canceled.</param>
public static async Task JsonSerializeAsync<T>(this FileInfo file, [DisallowNull] T value, [DisallowNull] JsonSerializerSettings settings, CancellationToken cancellationToken=default)
{
if (string.IsNullOrEmpty(file.DirectoryName) == true && Directory.Exists(file.DirectoryName) == false)
{
Directory.CreateDirectory(file.FullName);
}
using (var stream = file.OpenWrite())
{
await stream.JsonSerializeAsync(value, settings,bufferSize:1024,leaveOpen:false, cancellationToken).ConfigureAwait(false);
}
file.Refresh();
}
/// <summary>serialize the value in the stream.</summary>
/// <typeparam name="T">the type to serialize</typeparam>
/// <param name="stream">The stream.</param>
/// <param name="value">The value.</param>
/// <param name="settings">The json settings to use.</param>
/// <param name="bufferSize">The buffer size, in bytes, set -1 to not flush till done</param>
/// <param name="leaveOpen"> true to leave the stream open </param>
public static void JsonSerialize<T>(this Stream stream,[DisallowNull] T value, [DisallowNull] JsonSerializerSettings settings, int bufferSize=1024, bool leaveOpen=false)
{
using (var writer = new StreamWriter(stream,encoding: System.Text.Encoding.UTF32,bufferSize,leaveOpen))
using (var jsonWriter = new JsonTextWriter(writer))
{
var ser = JsonSerializer.Create( settings );
ser.Serialize(jsonWriter, value);
jsonWriter.Flush();
}
}
/// <summary>serialize the value in the stream asynchronously.</summary>
/// <typeparam name="T"></typeparam>
/// <param name="stream">The stream.</param>
/// <param name="value">The value.</param>
/// <param name="settings">The settings.</param>
/// <param name="bufferSize">The buffer size, in bytes, set -1 to not flush till done</param>
/// <param name="leaveOpen"> true to leave the stream open </param>
/// <param name="cancellationToken">Propagates notification that operations should be canceled.</param>
public static Task JsonSerializeAsync<T>(this Stream stream,[DisallowNull] T value, [DisallowNull] JsonSerializerSettings settings, int bufferSize=1024, bool leaveOpen=false, CancellationToken cancellationToken=default)
{
using (var writer = new StreamWriter(stream,encoding: System.Text.Encoding.UTF32,bufferSize: bufferSize,leaveOpen: leaveOpen))
using (var jsonWriter = new JsonTextWriter(writer))
{
var ser = JsonSerializer.Create( settings );
ser.Serialize(jsonWriter, value);
jsonWriter.Flush();
}
return Task.CompletedTask;
}
/// <summary>
/// Determines whether [is valid json] [the specified result].
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="stream">The stream.</param>
/// <param name="result">The result.</param>
/// <returns><c>true</c> if [is valid json] [the specified result]; otherwise, <c>false</c>.</returns>
public static bool IsValidJson<T>(this Stream stream, [NotNullWhen(true)] out T? result)
{
if (stream is null)
{
throw new ArgumentNullException(nameof(stream));
}
if (stream.Position != 0)
{
stream.Seek(0, SeekOrigin.Begin);
}
JsonSerializerSettings settings = (JsonConvert.DefaultSettings?.Invoke()) ?? new JsonSerializerSettings() { DateTimeZoneHandling = DateTimeZoneHandling.Utc, DateFormatHandling = DateFormatHandling.IsoDateFormat };
settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
using (var reader = new StreamReader(stream))
using (var jsonReader = new JsonTextReader(reader))
{
var ser = JsonSerializer.Create(settings);
try
{
result = ser.Deserialize<T>(jsonReader);
}
catch { result = default; }
}
return result is not null;
}
/// <summary>
/// Determines whether [is valid json] [the specified settings].
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="stream">The stream.</param>
/// <param name="settings">The settings.</param>
/// <param name="result">The result.</param>
/// <returns><c>true</c> if [is valid json] [the specified settings]; otherwise, <c>false</c>.</returns>
public static bool IsValidJson<T>(this Stream stream, JsonSerializerSettings settings, [NotNullWhen(true)] out T? result)
{
if (stream is null)
{
throw new ArgumentNullException(nameof(stream));
}
if (settings is null)
{
throw new ArgumentNullException(nameof(settings));
}
if (stream.Position != 0)
{
stream.Seek(0, SeekOrigin.Begin);
}
using (var reader = new StreamReader(stream))
using (var jsonReader = new JsonTextReader(reader))
{
var ser = JsonSerializer.Create(settings);
try
{
result = ser.Deserialize<T>(jsonReader);
}
catch { result = default; }
}
return result is not null;
}
/// <summary>
/// Determines whether file contains valid json using the specified settings and reads it into the output.
/// </summary>
/// <typeparam name="T">Type to convert into</typeparam>
/// <param name="file">The file.</param>
/// <param name="settings">The settings.</param>
/// <param name="result">The result.</param>
/// <returns><c>true</c> if [is valid json] [the specified settings]; otherwise, <c>false</c>.</returns>
/// <exception cref="System.ArgumentNullException">file</exception>
/// <exception cref="System.ArgumentNullException"></exception>
/// <exception cref="System.ArgumentNullException">settings</exception>
/// <exception cref="System.IO.FileNotFoundException">File could not be accessed</exception>
public static bool IsValidJson<T>(this FileInfo file, JsonSerializerSettings settings, [NotNullWhen(true)] out T? result)
{
if (file is null)
{
throw new ArgumentNullException(nameof(file));
}
if (File.Exists(file.FullName) == false)
{
throw new FileNotFoundException("File could not be accessed",fileName: file.FullName);
}
using var stream = file.OpenRead();
if (stream is null)
{
throw new ArgumentNullException(message:"Could not open the file and access the underlying file stream",paramName: nameof(file));
}
if (settings is null)
{
throw new ArgumentNullException(nameof(settings));
}
using (var reader = new StreamReader(stream))
using (var jsonReader = new JsonTextReader(reader))
{
var ser = JsonSerializer.Create(settings);
try
{
result = ser.Deserialize<T>(jsonReader);
}
catch { result = default; }
}
return result is not null;
}
/// <summary>
/// Determines whether file contains valid json using the specified settings and reads it into the output.
/// </summary>
/// <typeparam name="T">Type to convert into</typeparam>
/// <param name="file">The file.</param>
/// <param name="result">The result.</param>
/// <returns><c>true</c> if [is valid json] [the specified result]; otherwise, <c>false</c>.</returns>
/// <exception cref="System.ArgumentNullException">file</exception>
/// <exception cref="System.IO.FileNotFoundException">File could not be accessed</exception>
public static bool IsValidJson<T>(this FileInfo file, [NotNullWhen(true)] out T? result)
{
if (file is null)
{
throw new ArgumentNullException(nameof(file));
}
if (File.Exists(file.FullName) == false)
{
throw new FileNotFoundException("File could not be accessed",fileName: file.FullName);
}
JsonSerializerSettings settings =( JsonConvert.DefaultSettings?.Invoke()) ?? new JsonSerializerSettings() { DateTimeZoneHandling= DateTimeZoneHandling.Utc, DateFormatHandling= DateFormatHandling.IsoDateFormat };
settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
return file.IsValidJson<T>(settings,out result);
}
}
I used https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-2.1&tabs=visual-studio#xml-comments to show my classes summaries description in SwaggerUI, it's OK but not show enum summary description !
My startup.cs
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "My App-Service",
Description = "My Description",
});
c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"));
c.DescribeAllEnumsAsStrings();
});
My enum:
public enum GenderEnum
{
/// <summary>
/// Man Description
/// </summary>
Man = 1,
/// <summary>
/// Woman Description
/// </summary>
Woman = 2
}
It shows something like following:
I want to show Man Description and Woman Description in SwaggerUI
like this:
Man = 1, Man Description
Woman = 2, Woman Description
I'm using Swashbuckle.AspNetCore v4.0.1 package
As of June/2021 OpenApi now supports this and you can extend Swagger to show the details. Here is my code for C# on .NET 5.0.
First define the schema filter in a file (call it DescribeEnumMembers.cs and be sure to change YourNamespace to the name of your namespace):
using System;
using System.Text;
using System.Xml.Linq;
using System.Xml.XPath;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace YourNamespace
{
/// <summary>
/// Swagger schema filter to modify description of enum types so they
/// show the XML docs attached to each member of the enum.
/// </summary>
public class DescribeEnumMembers: ISchemaFilter
{
private readonly XDocument mXmlComments;
/// <summary>
/// Initialize schema filter.
/// </summary>
/// <param name="argXmlComments">Document containing XML docs for enum members.</param>
public DescribeEnumMembers(XDocument argXmlComments)
=> mXmlComments = argXmlComments;
/// <summary>
/// Apply this schema filter.
/// </summary>
/// <param name="argSchema">Target schema object.</param>
/// <param name="argContext">Schema filter context.</param>
public void Apply(OpenApiSchema argSchema, SchemaFilterContext argContext) {
var EnumType = argContext.Type;
if(!EnumType.IsEnum) return;
var sb = new StringBuilder(argSchema.Description);
sb.AppendLine("<p>Possible values:</p>");
sb.AppendLine("<ul>");
foreach(var EnumMemberName in Enum.GetNames(EnumType)) {
var FullEnumMemberName = $"F:{EnumType.FullName}.{EnumMemberName}";
var EnumMemberDescription = mXmlComments.XPathEvaluate(
$"normalize-space(//member[#name = '{FullEnumMemberName}']/summary/text())"
) as string;
if(string.IsNullOrEmpty(EnumMemberDescription)) continue;
sb.AppendLine($"<li><b>{EnumMemberName}</b>: {EnumMemberDescription}</li>");
}
sb.AppendLine("</ul>");
argSchema.Description = sb.ToString();
}
}
}
Then enable it in your ASP.NET ConfigureServices() method. Here is my code after snipping out the parts that don't matter for this exercise:
public void ConfigureServices(IServiceCollection argServices) {
// ...<snip other code>
argServices.AddSwaggerGen(SetSwaggerGenOptions);
// ...<snip other code>
return;
// ...<snip other code>
void SetSwaggerGenOptions(SwaggerGenOptions argOptions) {
// ...<snip other code>
AddXmlDocs();
return;
void AddXmlDocs() {
// generate paths for the XML doc files in the assembly's directory.
var XmlDocPaths = Directory.GetFiles(
path: AppDomain.CurrentDomain.BaseDirectory,
searchPattern: "YourAssemblyNameHere*.xml"
);
// load the XML docs for processing.
var XmlDocs = (
from DocPath in XmlDocPaths select XDocument.Load(DocPath)
).ToList();
// ...<snip other code>
// add pre-processed XML docs to Swagger.
foreach(var doc in XmlDocs) {
argOptions.IncludeXmlComments(() => new XPathDocument(doc.CreateReader()), true);
// apply schema filter to add description of enum members.
argOptions.SchemaFilter<DescribeEnumMembers>(doc);
}
}
}
}
Remember to change "YourAssemblyNameHere*.xml" to match your assembly name. The important line that enables the schema filter is:
argOptions.SchemaFilter<DescribeEnumMembers>(doc);
...which MUST be called AFTER the following line:
argOptions.IncludeXmlComments(() => new XPathDocument(doc.CreateReader()), true);
Using the above code, if you have an enum type defined like this for example:
/// <summary>
/// Setting to control when a no-match report is returned when searching.
/// </summary>
public enum NoMatchReportSetting
{
/// <summary>
/// Return no-match report only if the search query has no match.
/// </summary>
IfNoMatch = 0,
/// <summary>
/// Always return no-match report even if the search query has a match.
/// </summary>
Always = 1,
/// <summary>
/// Never return no-match report even if search query has no match.
/// </summary>
No = 99
}
The Swagger documentation will end up showing a description of each enum member as part of the description of the enum type itself:
This solution allows for
Show underlying value as well as name/description
Handle multiple xml documentation files, but only process docs once.
Customization of the layout without code change
Here's the class...
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml.XPath;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace YourNamespace
{
/// <summary>
/// Swagger schema filter to modify description of enum types so they
/// show the XML docs attached to each member of the enum.
/// </summary>
public class DescribeEnumMembers : ISchemaFilter
{
private readonly XDocument xmlComments;
private readonly string assemblyName;
/// <summary>
/// Initialize schema filter.
/// </summary>
/// <param name="xmlComments">Document containing XML docs for enum members.</param>
public DescribeEnumMembers(XDocument xmlComments)
{
this.xmlComments = xmlComments;
this.assemblyName = DetermineAssembly(xmlComments);
}
/// <summary>
/// Pre-amble to use before the enum items
/// </summary>
public static string Prefix { get; set; } = "<p>Possible values:</p>";
/// <summary>
/// Format to use, 0 : value, 1: Name, 2: Description
/// </summary>
public static string Format { get; set; } = "<b>{0} - {1}</b>: {2}";
/// <summary>
/// Apply this schema filter.
/// </summary>
/// <param name="schema">Target schema object.</param>
/// <param name="context">Schema filter context.</param>
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
var type = context.Type;
// Only process enums and...
if (!type.IsEnum)
{
return;
}
// ...only the comments defined in their origin assembly
if (type.Assembly.GetName().Name != assemblyName)
{
return;
}
var sb = new StringBuilder(schema.Description);
if (!string.IsNullOrEmpty(Prefix))
{
sb.AppendLine(Prefix);
}
sb.AppendLine("<ul>");
// TODO: Handle flags better e.g. Hex formatting
foreach (var name in Enum.GetValues(type))
{
// Allows for large enums
var value = Convert.ToInt64(name);
var fullName = $"F:{type.FullName}.{name}";
var description = xmlComments.XPathEvaluate(
$"normalize-space(//member[#name = '{fullName}']/summary/text())"
) as string;
sb.AppendLine(string.Format("<li>" + Format + "</li>", value, name, description));
}
sb.AppendLine("</ul>");
schema.Description = sb.ToString();
}
private string DetermineAssembly(XDocument doc)
{
var name = ((IEnumerable)doc.XPathEvaluate("/doc/assembly")).Cast<XElement>().ToList().FirstOrDefault();
return name?.Value;
}
}
}
and utilization...
services.AddSwaggerGen(c =>
{
...
// See https://github.com/domaindrivendev/Swashbuckle/issues/86
var dir = new DirectoryInfo(AppContext.BaseDirectory);
foreach (var fi in dir.EnumerateFiles("*.xml"))
{
var doc = XDocument.Load(fi.FullName);
c.IncludeXmlComments(() => new XPathDocument(doc.CreateReader()), true);
c.SchemaFilter<DescribeEnumMembers>(doc);
}
});
This then reports as
Unfortunately this does not seem to be supported in the OpenAPI specification. There is an open Github issue for this.
There is also an open Github issue for Swashbuckle.
However, in this issue there is a workaround to create a schema filter, which at least shows the enum value comments in the enum type description.
I solved this using a description attribute. Here is an example usage:
public enum GenderEnum
{
[Description("Man Description")]
Man = 1,
[Description("Woman Description")]
Woman = 2
}
I have an asp.net mvc 5 app with a database that stores photos. I'm trying to read the photo and resize it for display in a Staff profile.
I'm fairly new to both asp.net mvc and c#
I setup the following controller but am not getting an image display when I use a link to the controller in an img tag.
Any help would be appreciated.
public ActionResult Index(int id)
{
Staff staff = db.StaffList.Find(id);
if (staff.Photo != null)
{
var img = new WebImage(staff.Photo);
img.Resize(100, 100, true, true);
var imgBytes = img.GetBytes();
return File(imgBytes, "image/" + img.ImageFormat);
}
else
{
return null;
}
}
Looking around it seems there's a lot of dissatisfaction with the WebImage class and it has a few prominent bugs. I settled on using a nuget package called ImageProcessor rather than trying to write my own. This seems fairly inefficient to me but I don't have a better answer right now and this isn't heavily used so I'm going with this and just moving on.
Posting it here in case anyone else is struggling with something similar.
public ActionResult Index(int id, int? height, int? width)
{
int h = (height ?? 325);
int w = (width ?? 325);
Staff staff = db.StaffList.Find(id);
if (staff == null)
{
return new HttpNotFoundResult();
}
if (staff.Photo != null)
{
Size size = new Size(w, h);
byte[] rawImg;
using (MemoryStream inStream = new MemoryStream(staff.Photo))
{
using (MemoryStream outStream = new MemoryStream())
{
using (ImageFactory imageFactory = new ImageFactory())
{
imageFactory.Load(inStream)
.Constrain(size)
.Format(format)
.Save(outStream);
}
rawImg = outStream.ToArray();
}
}
return new FileContentResult(rawImg, "image/jpeg");
}
else
{
return null;
}
}
I'm going to answer this using ImageProcessor since your own answer uses the library. Disclaimer. I'm also the author of the library.
You're really not best using an ActionResult for processing images as it will be horribly inefficient. It run's far too late in the pipeline and you will have no caching.
You're much better off installing the Imageprocessor.Web package and implementing your own version of the IImageService interface to serve your images from the database. (On that note storing images in a db unless you are using blob storage is never wise either)
Implementing the IImageService interface allows you to utilise the url api within the library with a specific prefix to identify which image service to use. For example, remote image requests are prefixed with remote.axd to tell IageProcessor.Web to excute the RemoteImageService implementation.
This has the benefit of caching your images so subsequent requests are returned from a cache rather than being reprocessed upon each request.
Here is the full implementation of the LocalFileImageService which is the default service for the library. This should be able to serve as a guide for how to implement your own service.
namespace ImageProcessor.Web.Services
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Web;
using ImageProcessor.Web.Helpers;
/// <summary>
/// The local file image service for retrieving images from the
/// file system.
/// </summary>
public class LocalFileImageService : IImageService
{
/// <summary>
/// The prefix for the given implementation.
/// </summary>
private string prefix = string.Empty;
/// <summary>
/// Gets or sets the prefix for the given implementation.
/// <remarks>
/// This value is used as a prefix for any image requests
/// that should use this service.
/// </remarks>
/// </summary>
public string Prefix
{
get
{
return this.prefix;
}
set
{
this.prefix = value;
}
}
/// <summary>
/// Gets a value indicating whether the image service
/// requests files from
/// the locally based file system.
/// </summary>
public bool IsFileLocalService
{
get
{
return true;
}
}
/// <summary>
/// Gets or sets any additional settings required by the service.
/// </summary>
public Dictionary<string, string> Settings { get; set; }
/// <summary>
/// Gets or sets the white list of <see cref="System.Uri"/>.
/// </summary>
public Uri[] WhiteList { get; set; }
/// <summary>
/// Gets a value indicating whether the current request
/// passes sanitizing rules.
/// </summary>
/// <param name="path">
/// The image path.
/// </param>
/// <returns>
/// <c>True</c> if the request is valid; otherwise, <c>False</c>.
/// </returns>
public bool IsValidRequest(string path)
{
return ImageHelpers.IsValidImageExtension(path);
}
/// <summary>
/// Gets the image using the given identifier.
/// </summary>
/// <param name="id">
/// The value identifying the image to fetch.
/// </param>
/// <returns>
/// The <see cref="System.Byte"/> array containing the image data.
/// </returns>
public async Task<byte[]> GetImage(object id)
{
string path = id.ToString();
byte[] buffer;
// Check to see if the file exists.
// ReSharper disable once AssignNullToNotNullAttribute
FileInfo fileInfo = new FileInfo(path);
if (!fileInfo.Exists)
{
throw new HttpException(404, "No image exists at " + path);
}
using (FileStream file = new FileStream(path,
FileMode.Open,
FileAccess.Read,
FileShare.Read,
4096,
true))
{
buffer = new byte[file.Length];
await file.ReadAsync(buffer, 0, (int)file.Length);
}
return buffer;
}
}
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Looking to get the email id along with the openid while
Using the Internet template for MVC4
This is available for auth using google but not for facebook
wondering how to get/request the email id in the extraData dictionary
Looking at the code in AspNetWebStack project at http://aspnetwebstack.codeplex.com/, it looks like
OAuthWebSecurity.RegisterFacebookClient()
makes use of FacebookClient in DotNetOpenAuth.AspNet.dll hosted at https://github.com/AArnott/dotnetopenid
and the code in FacebookClient.GetUserData() has
var userData = new NameValueCollection();
userData.AddItemIfNotEmpty("id", graphData.Id);
userData.AddItemIfNotEmpty("username", graphData.Email);
userData.AddItemIfNotEmpty("name", graphData.Name);
userData.AddItemIfNotEmpty("link", graphData.Link == null ? null : graphData.Link.AbsoluteUri);
userData.AddItemIfNotEmpty("gender", graphData.Gender);
userData.AddItemIfNotEmpty("birthday", graphData.Birthday);
return userData;
which should return the email-id in username but it's not being returned
any help is appreciated
thanks
The provided Facebook OAuth client will not let you get anything beyond the default info. To get anything else, you need to be able to change the value of the scope parameter, something the included client doesn't allow. So, to get around this and still use the other boilerplate code the Internet template provides, you need to implement a custom OAuth client that follows the same pattern.
Since the entire ASP.NET source is open source, as is the OAuth library DotNetOpenAuth, you can actually look into the OAuth library and see exactly how the Facebook provider is built. Using that, I was able to come up with this:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Web;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.AspNet;
using DotNetOpenAuth.AspNet.Clients;
using Validation;
using Newtonsoft.Json;
namespace OAuthProviders
{
/// <summary>
/// The facebook client.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Facebook", Justification = "Brand name")]
public sealed class FacebookScopedClient : OAuth2Client
{
#region Constants and Fields
/// <summary>
/// The authorization endpoint.
/// </summary>
private const string AuthorizationEndpoint = "https://www.facebook.com/dialog/oauth";
/// <summary>
/// The token endpoint.
/// </summary>
private const string TokenEndpoint = "https://graph.facebook.com/oauth/access_token";
/// <summary>
/// The _app id.
/// </summary>
private readonly string appId;
/// <summary>
/// The _app secret.
/// </summary>
private readonly string appSecret;
private readonly string scope;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="FacebookScopedClient"/> class.
/// </summary>
/// <param name="appId">
/// The app id.
/// </param>
/// <param name="appSecret">
/// The app secret.
/// </param>
/// <param name="scope">
/// The scope (requested Facebook permissions).
/// </param>
public FacebookScopedClient(string appId, string appSecret, string scope)
: base("facebook")
{
Requires.NotNullOrEmpty(appId, "appId");
Requires.NotNullOrEmpty(appSecret, "appSecret");
Requires.NotNullOrEmpty(scope, "scope");
this.appId = appId;
this.appSecret = appSecret;
this.scope = scope;
}
#endregion
#region Methods
/// <summary>
/// The get service login url.
/// </summary>
/// <param name="returnUrl">
/// The return url.
/// </param>
/// <returns>An absolute URI.</returns>
protected override Uri GetServiceLoginUrl(Uri returnUrl)
{
// Note: Facebook doesn't like us to url-encode the redirect_uri value
var builder = new UriBuilder(AuthorizationEndpoint);
builder.AppendQueryArgument("client_id", this.appId);
builder.AppendQueryArgument("redirect_uri", returnUrl.AbsoluteUri);
builder.AppendQueryArgument("scope", this.scope);
return builder.Uri;
}
/// <summary>
/// The get user data.
/// </summary>
/// <param name="accessToken">
/// The access token.
/// </param>
/// <returns>A dictionary of profile data.</returns>
protected override IDictionary<string, string> GetUserData(string accessToken)
{
FacebookGraphData graphData;
var request =
WebRequest.Create("https://graph.facebook.com/me?access_token=" + UriDataStringRFC3986(accessToken));
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
graphData = OAuthJsonHelper.Deserialize<FacebookGraphData>(responseStream);
}
}
// this dictionary must contains
var userData = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(graphData.Id)) { userData.Add("id", graphData.Id); }
if (!string.IsNullOrEmpty(graphData.Email)) { userData.Add("username", graphData.Email); }
if (!string.IsNullOrEmpty(graphData.Name)) { userData.Add("name", graphData.Name); }
if (graphData.Link != null && !string.IsNullOrEmpty(graphData.Link.AbsoluteUri)) { userData.Add("link", graphData.Link == null ? null : graphData.Link.AbsoluteUri); }
if (!string.IsNullOrEmpty(graphData.Gender)) { userData.Add("gender", graphData.Gender); }
if (!string.IsNullOrEmpty(graphData.Birthday)) { userData.Add("birthday", graphData.Birthday); }
return userData;
}
/// <summary>
/// Obtains an access token given an authorization code and callback URL.
/// </summary>
/// <param name="returnUrl">
/// The return url.
/// </param>
/// <param name="authorizationCode">
/// The authorization code.
/// </param>
/// <returns>
/// The access token.
/// </returns>
protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
{
// Note: Facebook doesn't like us to url-encode the redirect_uri value
var builder = new UriBuilder(TokenEndpoint);
builder.AppendQueryArgument("client_id", this.appId);
builder.AppendQueryArgument("redirect_uri", NormalizeHexEncoding(returnUrl.AbsoluteUri));
builder.AppendQueryArgument("client_secret", this.appSecret);
builder.AppendQueryArgument("code", authorizationCode);
builder.AppendQueryArgument("scope", this.scope);
using (WebClient client = new WebClient())
{
string data = client.DownloadString(builder.Uri);
if (string.IsNullOrEmpty(data))
{
return null;
}
var parsedQueryString = HttpUtility.ParseQueryString(data);
return parsedQueryString["access_token"];
}
}
/// <summary>
/// Converts any % encoded values in the URL to uppercase.
/// </summary>
/// <param name="url">The URL string to normalize</param>
/// <returns>The normalized url</returns>
/// <example>NormalizeHexEncoding("Login.aspx?ReturnUrl=%2fAccount%2fManage.aspx") returns "Login.aspx?ReturnUrl=%2FAccount%2FManage.aspx"</example>
/// <remarks>
/// There is an issue in Facebook whereby it will rejects the redirect_uri value if
/// the url contains lowercase % encoded values.
/// </remarks>
private static string NormalizeHexEncoding(string url)
{
var chars = url.ToCharArray();
for (int i = 0; i < chars.Length - 2; i++)
{
if (chars[i] == '%')
{
chars[i + 1] = char.ToUpperInvariant(chars[i + 1]);
chars[i + 2] = char.ToUpperInvariant(chars[i + 2]);
i += 2;
}
}
return new string(chars);
}
/// <summary>
/// The set of characters that are unreserved in RFC 2396 but are NOT unreserved in RFC 3986.
/// </summary>
private static readonly string[] UriRfc3986CharsToEscape = new[] { "!", "*", "'", "(", ")" };
internal static string UriDataStringRFC3986(string value)
{
// Start with RFC 2396 escaping by calling the .NET method to do the work.
// This MAY sometimes exhibit RFC 3986 behavior (according to the documentation).
// If it does, the escaping we do that follows it will be a no-op since the
// characters we search for to replace can't possibly exist in the string.
var escaped = new StringBuilder(Uri.EscapeDataString(value));
// Upgrade the escaping to RFC 3986, if necessary.
for (int i = 0; i < UriRfc3986CharsToEscape.Length; i++)
{
escaped.Replace(UriRfc3986CharsToEscape[i], Uri.HexEscape(UriRfc3986CharsToEscape[i][0]));
}
// Return the fully-RFC3986-escaped string.
return escaped.ToString();
}
#endregion
}
}
There are a few dependent libraries required to make this work as-is, all of which are available on NuGet. You already have DotNetOpenAuth; http://nuget.org/packages/Validation/ is another. The OAuthJsonHelper is a copy of an internal class used by DotNetOpenAuth - to get this provider to work I had to re-implement it in my own namespace:
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using Validation;
namespace OAuthProviders
{
/// <summary>
/// The JSON helper.
/// </summary>
internal static class OAuthJsonHelper
{
#region Public Methods and Operators
/// <summary>
/// The deserialize.
/// </summary>
/// <param name="stream">
/// The stream.
/// </param>
/// <typeparam name="T">The type of the value to deserialize.</typeparam>
/// <returns>
/// The deserialized value.
/// </returns>
public static T Deserialize<T>(Stream stream) where T : class
{
Requires.NotNull(stream, "stream");
var serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(stream);
}
#endregion
}
}
This is all provided as-is, with no guarantee that it will work via copy/paste - it's up to you to figure out how to integrate it into your project.
I have an object exposed through a web service that is consumed by another system. That system also uses that same WSDL to return back an object on demand to us. I was wondering if it was possible to take that same object and relay it back to a the original object?
I tried to do the following and it wouldn't actually cast it back with the object populated... Any help would be great!
Thank you!
Note The method code listed below was based off of http://www.dotnetjohn.com/articles.aspx?articleid=173
public void ConvertBack()
{
ThirdParty.Animal animal;
using (var svc = new ThirdPartySoapClient())
thirdPartyAnimal = svc.GetAnimal("Identifier");
var xml = SerializeObject(thirdPartyAnimal, typeof(ThirdParty.Animal));
var originalAnimal = (OriginalNamespace.Animal)DeserializeObject(xml, typeof(OrginalNamespace.Animal));
Assert.AreEqual(originalAnimal.Name, animal.Name);
}
/// <summary>
/// Method to convert a custom Object to XML string
/// </summary>
/// <param name="pObject">Object that is to be serialized to XML</param>
/// <param name="typeOfObject">typeof() object that is being passed to be serialized to XML</param>
/// <returns>XML string</returns>
public string SerializeObject(object pObject, Type typeOfObject)
{
try
{
var memoryStream = new MemoryStream();
var xs = new XmlSerializer(typeOfObject);
var xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, pObject);
memoryStream = (MemoryStream) xmlTextWriter.BaseStream;
var xmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return xmlizedString;
}
catch (Exception e)
{
Console.WriteLine(e);
return null;
}
}
/// <summary>
/// Method to reconstruct an Object from XML string
/// </summary>
/// <param name="pXmlizedString">XML To Be Converted to an Object</param>
/// <param name="typeOfObject">typeof() object that is being passed to be serialized to XML</param>
/// <returns></returns>
public object DeserializeObject(string pXmlizedString, Type typeOfObject)
{
var xs = new XmlSerializer(typeOfObject);
var memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
new XmlTextWriter(memoryStream, Encoding.UTF8);
return xs.Deserialize(memoryStream);
}
/// <summary>
/// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
/// </summary>
/// <param name="characters">Unicode Byte Array to be converted to String</param>
/// <returns>String converted from Unicode Byte Array</returns>
private static string UTF8ByteArrayToString(Byte[] characters)
{
var encoding = new UTF8Encoding();
var constructedString = encoding.GetString(characters);
return (constructedString);
}
/// <summary>
/// Converts the String to UTF8 Byte array and is used in De serialization
/// </summary>
/// <param name="pXmlString"></param>
/// <returns></returns>
private static Byte[] StringToUTF8ByteArray(string pXmlString)
{
var encoding = new UTF8Encoding();
var byteArray = encoding.GetBytes(pXmlString);
return byteArray;
}
When generating the proxy from WSDL there is an option called "/sharetypes" which should solve this problem
You can use it from the command line tools or in the options area of the "Add Web Service" dialogs