Monday afternoon I was working on a web service, was able to request the .asmx file in the browser and was given the menu of usable methods and was able to invoke them from the browser with no problems. Tuesday comes around and each time I access it, I get an "Object moved to here" message that links to a nonexistent login.aspx page.
Here's the .asmx.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data.SqlClient;
namespace LegacyReports
{
/// <summary>
/// Summary description for Example
/// </summary>
[WebService(Namespace = "http://company.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
//[System.Web.Script.Services.ScriptService]
public class Example : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public List<ExampleData> ExampleDataSet()
{
Context.Database db = new Context.Database();
String sql = #"SELECT TOP 10 * FROM sometable";
SqlDataReader reader = db.ExecuteReader(sql);
List<ExampleData> data = new List<ExampleData>();
while (reader.Read())
{
int a = Convert.ToInt32(reader["somecolumn"]);
String b = (String)reader["anothercolumn"] + " " + (String)reader["someotherrandomcolumn"];
data.Add(new ExampleData() { a = a, b = b });
}
return data;
}
}
public class ExampleData
{
public int a { get; set; }
public String b { get; set; }
}
}
I'm just not sure why it would work one day then stop the next day. Could it be something with IIS?
Related
i'm trying to read and write to a file.
for the first part, writing list of objects to a binary file, i succeed to do so using serialization.
the problem was when i tried to read the back from the file to a list of objects, using deserialize. every time that i'm running the solution i get a runtime error.
the code:
using System;
using System.IO;
using MileStone1Fin.LogicLayer;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Newtonsoft.Json;
namespace MileStone1Fin.PersistentLayer
{
public class UserHandler
{
public UserHandler()
{
}
public void addNewUser(List<User> users)
{
Stream myFileStream = File.Create("UsersData.bin");
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(myFileStream, users);
Console.WriteLine("5535");
myFileStream.Close();
List<User> newUsers1 = null;
if (File.Exists("UsersData.bin"))
{
Stream myFileStream1 = File.OpenRead("UsersData.bin");
BinaryFormatter bf1 = new BinaryFormatter();
newUsers1 = (List<User>)bf1.Deserialize(myFileStream1);//this line marked as the problem one according to visual studio
myFileStream1.Close();
}
}
}
}
Line 38 is the problematic line
The code that made the call:
public void registration(String nickname, String groupID)
{
if(checkUserValidity(nickname, groupID))
{
User newUser = new User(nickname, groupID);
users.Add(newUser);
userHandler.addNewUser(users);
User class:
System.Reflection.TargetInvocationExeption - the runtime error
using System;
using Newtonsoft.Json;
using MileStoneClient.CommunicationLayer;
using MileStone1Fin.PersistentLayer;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace MileStone1Fin.LogicLayer
{
///<summary>
/// This class taking care for the functionallity of the user objects.
/// The user class will be part of the Logic layer
/// </summary>
[Serializable()]
public class User : ISerializable
{
private static UserHandler userHandler = new UserHandler();
private String nickname { get; set; }
private String groupID { get; set; }
private bool status { get; set; }
DateTime lastSeen { get; set; }
public User(String nickname, String groupID) //The User class constructor
{
this.nickname = nickname;
this.groupID = groupID;
this.lastSeen = DateTime.Now;
this.status = false;
}
/*public Message send(String msg) //Creates a Imessage object, return a Message object contains GUID, time, user
{ //information, message body
IMessage message = Communication.Instance.Send(ChatRoom.url, this.groupID, this.nickname, msg);//sends the neccesary details to the server
return new Message(message);
}*/
public void logout()
{
this.status = false;
//Console.WriteLine(this.nickname + "You were disconnected from the server");
lastSeen = DateTime.Now;
//Console.WriteLine(lastSeen);
//need to write into file
}
private bool isOnline()
{
return this.status;
}
public void lastSeenDate()
{
if (isOnline())
Console.WriteLine("Online now");
else
Console.WriteLine(lastSeen.ToString());
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Nickname", nickname);
info.AddValue("GroupId", groupID);
info.AddValue("LastSeen", lastSeen);
info.AddValue("Status", status);
}
public User(SerializationInfo info, StreamingContext context)
{
nickname = (string)info.GetValue("Name", typeof(string));
groupID = (string)info.GetValue("GroupId", typeof(string));
lastSeen = (DateTime)info.GetValue("LastSeen", typeof(DateTime));
status = (Boolean)info.GetValue("Status", typeof(Boolean));
}
}
}
The issue is how you are naming things with serialization, you are serializing Nickname and trying to read it out as Name. The safest thing to do is to get the name right from the property:
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(nameof(nickname), nickname);
info.AddValue(nameof(groupID), groupID);
info.AddValue(nameof(lastSeen), lastSeen);
info.AddValue(nameof(status), status);
}
public User(SerializationInfo info, StreamingContext context)
{
nickname = (string)info.GetValue(nameof(nickname), typeof(string));
groupID = (string)info.GetValue(nameof(groupID), typeof(string));
lastSeen = (DateTime)info.GetValue(nameof(lastSeen), typeof(DateTime));
status = (Boolean)info.GetValue(nameof(status), typeof(Boolean));
}
}
Which has the added benefit of when you rename your properties (to the .NET standard), it will automatically rename your code as well. This can cause issues if you rename something and then try to load an old file, so be careful, but at least this way you don't have magic strings floating around in your code. You can avoid the above problem by writing version information to the serialization stream and deserializing based on a version.
Is it possible to include a web.config or app.config file in the azure functions folder structure to allow assembly binding redirects?
Assuming you are using the latest (June'17) Visual Studio 2017 Function Tooling, I derived a somewhat-reasonable config-based solution for this following a snippet of code posted by npiasecki over on Issue #992.
It would be ideal if this were managed through the framework, but at least being configuration-driven you have a bit more change isolation. I suppose you could also use some pre-build steps or T4 templating that reconciles the versions of the nugets in the project (and their dependencies) before writing out this config or generating code.
So the downside..
.. becomes having to remember to update the BindingRedirects config when you update the NuGet package (this is often a problem in app.configs anyway). You may also have an issue with the config-driven solution if you need to redirect Newtonsoft.
In our case, we were using the new Azure Fluent NuGet that had a dependency on an older version of Microsoft.IdentityModel.Clients.ActiveDirectory than the version of the normal ARM management libraries which are used side-by-side in a particular Function.
local.settings.json
{
"IsEncrypted": false,
"Values": {
"BindingRedirects": "[ { \"ShortName\": \"Microsoft.IdentityModel.Clients.ActiveDirectory\", \"RedirectToVersion\": \"3.13.9.1126\", \"PublicKeyToken\": \"31bf3856ad364e35\" } ]"
}
}
FunctionUtilities.cs
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Utilities.AzureFunctions
{
public static class FunctionUtilities
{
public class BindingRedirect
{
public string ShortName { get; set; }
public string PublicKeyToken { get; set; }
public string RedirectToVersion { get; set; }
}
public static void ConfigureBindingRedirects()
{
var config = Environment.GetEnvironmentVariable("BindingRedirects");
var redirects = JsonConvert.DeserializeObject<List<BindingRedirect>>(config);
redirects.ForEach(RedirectAssembly);
}
public static void RedirectAssembly(BindingRedirect bindingRedirect)
{
ResolveEventHandler handler = null;
handler = (sender, args) =>
{
var requestedAssembly = new AssemblyName(args.Name);
if (requestedAssembly.Name != bindingRedirect.ShortName)
{
return null;
}
var targetPublicKeyToken = new AssemblyName("x, PublicKeyToken=" + bindingRedirect.PublicKeyToken)
.GetPublicKeyToken();
requestedAssembly.Version = new Version(bindingRedirect.RedirectToVersion);
requestedAssembly.SetPublicKeyToken(targetPublicKeyToken);
requestedAssembly.CultureInfo = CultureInfo.InvariantCulture;
AppDomain.CurrentDomain.AssemblyResolve -= handler;
return Assembly.Load(requestedAssembly);
};
AppDomain.CurrentDomain.AssemblyResolve += handler;
}
}
}
Just posted a new blog post explaining how to fix the problem, have a look:
https://codopia.wordpress.com/2017/07/21/how-to-fix-the-assembly-binding-redirect-problem-in-azure-functions/
It's actually a tweaked version of the JoeBrockhaus's code, that works well even for Newtonsoft.Json.dll
Inspired by the accepted answer I figured I'd do a more generic one which takes into account upgrades as well.
It fetches all assemblies, orders them descending to get the newest version on top, then returns the newest version on resolve. I call this in a static constructor myself.
public static void RedirectAssembly()
{
var list = AppDomain.CurrentDomain.GetAssemblies()
.Select(a => a.GetName())
.OrderByDescending(a => a.Name)
.ThenByDescending(a => a.Version)
.Select(a => a.FullName)
.ToList();
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
var requestedAssembly = new AssemblyName(args.Name);
foreach (string asmName in list)
{
if (asmName.StartsWith(requestedAssembly.Name + ","))
{
return Assembly.Load(asmName);
}
}
return null;
};
}
It is not directly possible today, but we are thinking about ways to achieve this. Can you please open an issue on https://github.com/Azure/azure-webjobs-sdk-script/issues to make sure your specific scenario is looked at? Thanks!
First SO post, so apologies if formatting's a bit off.
We've hit this issue a couple of times and managed to find a better way of getting the required redirects by forcing MSBUILD to generate a binding redirects file and then parsing that to be used with the previously suggested answer.
Modify the project settings and add in a couple of targets:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
...
<AutoGenerateBindingRedirects>True</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
...
</PropertyGroup>
</Project>
These classes apply the binding redirects using the same idea that was posted earlier (link) except instead of using the host.json file it reads from the generated binding redirects file. The filename to use is from reflection using the ExecutingAssembly.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;
public static class AssemblyBindingRedirectHelper
{
private static FunctionRedirectBindings _redirects;
public static void ConfigureBindingRedirects()
{
// Only load the binding redirects once
if (_redirects != null)
return;
_redirects = new FunctionRedirectBindings();
foreach (var redirect in _redirects.BindingRedirects)
{
RedirectAssembly(redirect);
}
}
public static void RedirectAssembly(BindingRedirect bindingRedirect)
{
ResolveEventHandler handler = null;
handler = (sender, args) =>
{
var requestedAssembly = new AssemblyName(args.Name);
if (requestedAssembly.Name != bindingRedirect.ShortName)
{
return null;
}
var targetPublicKeyToken = new AssemblyName("x, PublicKeyToken=" + bindingRedirect.PublicKeyToken).GetPublicKeyToken();
requestedAssembly.Version = new Version(bindingRedirect.RedirectToVersion);
requestedAssembly.SetPublicKeyToken(targetPublicKeyToken);
requestedAssembly.CultureInfo = CultureInfo.InvariantCulture;
AppDomain.CurrentDomain.AssemblyResolve -= handler;
return Assembly.Load(requestedAssembly);
};
AppDomain.CurrentDomain.AssemblyResolve += handler;
}
}
public class FunctionRedirectBindings
{
public HashSet<BindingRedirect> BindingRedirects { get; } = new HashSet<BindingRedirect>();
public FunctionRedirectBindings()
{
var assm = Assembly.GetExecutingAssembly();
var bindingRedirectFileName = $"{assm.GetName().Name}.dll.config";
var dir = Path.Combine(Environment.GetEnvironmentVariable("HOME"), #"site\wwwroot");
var fullPath = Path.Combine(dir, bindingRedirectFileName);
if(!File.Exists(fullPath))
throw new ArgumentException($"Could not find binding redirect file. Path:{fullPath}");
var xml = ReadFile<configuration>(fullPath);
TransformData(xml);
}
private T ReadFile<T>(string path)
{
using (StreamReader reader = new StreamReader(path))
{
var serializer = new XmlSerializer(typeof(T));
var obj = (T)serializer.Deserialize(reader);
reader.Close();
return obj;
}
}
private void TransformData(configuration xml)
{
foreach(var item in xml.runtime)
{
var br = new BindingRedirect
{
ShortName = item.dependentAssembly.assemblyIdentity.name,
PublicKeyToken = item.dependentAssembly.assemblyIdentity.publicKeyToken,
RedirectToVersion = item.dependentAssembly.bindingRedirect.newVersion
};
BindingRedirects.Add(br);
}
}
}
public class BindingRedirect
{
public string ShortName { get; set; }
public string PublicKeyToken { get; set; }
public string RedirectToVersion { get; set; }
}
Xml classes to use to deserialise the generated binding redirect file into something easier to use. These were generated from the binding redirects file by using VS2017 "paste special -> paste xml as classes" so feel free to roll your own if needed.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;
// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class configuration
{
[System.Xml.Serialization.XmlArrayItemAttribute("assemblyBinding", Namespace = "urn:schemas-microsoft-com:asm.v1", IsNullable = false)]
public assemblyBinding[] runtime { get; set; }
}
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "urn:schemas-microsoft-com:asm.v1")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "urn:schemas-microsoft-com:asm.v1", IsNullable = false)]
public partial class assemblyBinding
{
public assemblyBindingDependentAssembly dependentAssembly { get; set; }
}
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "urn:schemas-microsoft-com:asm.v1")]
public partial class assemblyBindingDependentAssembly
{
public assemblyBindingDependentAssemblyAssemblyIdentity assemblyIdentity { get; set; }
public assemblyBindingDependentAssemblyBindingRedirect bindingRedirect { get; set; }
}
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "urn:schemas-microsoft-com:asm.v1")]
public partial class assemblyBindingDependentAssemblyAssemblyIdentity
{
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute()]
public string publicKeyToken { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute()]
public string culture { get; set; }
}
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "urn:schemas-microsoft-com:asm.v1")]
public partial class assemblyBindingDependentAssemblyBindingRedirect
{
[System.Xml.Serialization.XmlAttributeAttribute()]
public string oldVersion { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute()]
public string newVersion { get; set; }
}
Here's an alternate solution for when you want the exact version of a particular assembly. With this code, you can easily deploy the assemblies that are missing:
public static class AssemblyHelper
{
//--------------------------------------------------------------------------------
/// <summary>
/// Redirection hack because Azure functions don't support it.
/// How to use:
/// If you get an error that a certain version of a dll can't be found:
/// 1) deploy that particular dll in any project subfolder
/// 2) In your azure function static constructor, Call
/// AssemblyHelper.IncludeSupplementalDllsWhenBinding()
///
/// This will hook the binding calls and look for a matching dll anywhere
/// in the $HOME folder tree.
/// </summary>
//--------------------------------------------------------------------------------
public static void IncludeSupplementalDllsWhenBinding()
{
var searching = false;
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
// This prevents a stack overflow
if(searching) return null;
var requestedAssembly = new AssemblyName(args.Name);
searching = true;
Assembly foundAssembly = null;
try
{
foundAssembly = Assembly.Load(requestedAssembly);
}
catch(Exception e)
{
Debug.WriteLine($"Could not load assembly: {args.Name} because {e.Message}");
}
searching = false;
if(foundAssembly == null)
{
var home = Environment.GetEnvironmentVariable("HOME") ?? ".";
var possibleFiles = Directory.GetFiles(home, requestedAssembly.Name + ".dll", SearchOption.AllDirectories);
foreach (var file in possibleFiles)
{
var possibleAssembly = AssemblyName.GetAssemblyName(file);
if (possibleAssembly.Version == requestedAssembly.Version)
{
foundAssembly = Assembly.Load(possibleAssembly);
break;
}
}
}
return foundAssembly;
};
}
}
I am trying to learn web services. My problem is I have created a class "Item" as follows,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WebServiceTaxCalc
{
public enum Type { BASIC, IMPORTED, EXEMPT}
public class Item
{
string name;
double basePrice;
int quantity;
Type TaxType;
public Item(string name, double price, int quantity, Type type)
{
this.basePrice = price;
this.name = name;
this.quantity = quantity;
this.TaxType = type;
}
public string getName()
{
return name;
}
public double getPrice()
{ return basePrice; }
public int getQuantity()
{ return quantity; }
public Type getType() { return TaxType; }
}
}
and another class for calculating the tax:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WebServiceTaxCalc
{
public class ShoppingBasket
{
double itemsTotalPrice = 0.0;
double totalTax = 0.0;
public void addItem(List<Item> i)
{
foreach (Item a in i)
{
totalTax += taxPerItem(a);
double eachItemPrice = (a.getPrice() + taxPerItem(a));
itemsTotalPrice += eachItemPrice;
//Console.WriteLine(a.getQuantity() + " " + a.getName() + ": " + eachItemPrice);
}
//Console.WriteLine("sales tax: " + totalTax);
//Console.WriteLine("total cost: "+itemsTotalPrice);
}
public double taxPerItem(Item i)
{
double tax = 0;
if (i.getType() == Type.BASIC)
{
tax = i.getPrice() * 5 / 100;
return tax;
}
else if (i.getType() == Type.EXEMPT)
{
tax = 0;
return tax;
}
else
{
tax = i.getPrice() * 15 / 100;
return tax;
}
}
}
}
I am trying to pass the values to the web service and let the web service call the classes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace WebServiceTaxCalc
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public ShoppingBasket Calc(string name, double price, int quantity, Type catg)
{
List<Item> l1 = new List<Item>();
Item i1 = new Item(name, price, quantity,catg);
l1.Add(i1);
ShoppingBasket sb = new ShoppingBasket();
sb.addItem(l1);
return sb;
}
}
}
I am giving the input like this,
input image:
and after invoking I am just getting this:
Output image
I am not getting the document tree of what I passed.
I have seen a useful post here https://stackoverflow.com/a/12039010/3768995
But I couldn't solve my problem.
Please guide me through this.
Add a [DataContract] attribute to ShoppingBasket and a [DataMember] attribute to the properties that need to be included when the response is sent. (And as was said, make them public properties.)
when i run a method within my WCF service i get "An unhandled exception of type 'System.StackOverflowException' occurred in developer1SVC.dll".
No infinite loops exist and no infinite recursion is occurring. Any ideas to why this may be happening? when i run the method through wcf test client. I get the results back correctly however, hooking it up to my console app and running it breaks the application. The other methods run fine. It is this one method. Just trying to get the feel for WCF services. The service breaks right after i return accounts from the "generateMultiplAccounts" method.
Much help appreciated.
Service
using developer1.Core.ServiceContracts;
using developer1.Core.Data;
using developer1.Core.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using developer1.Core.Dto.Account;
namespace developer1.Core.Service
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
Console.WriteLine(composite.StringValue + composite.BoolValue);
return composite;
}
public List<AccountDto> GenerateMultipleAccounts(int count)
{
List<AccountDto> accounts = new List<AccountDto>();
for (int i = 0; i < count; i++)
{
AccountDto newAccount = new AccountDto() { AccountId = Guid.NewGuid()};
accounts.Add(newAccount);
}
return accounts;
}
}
}
Console Application
using developer1.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using developer1.Core.Service;
using developer1.Core.Dto.Account;
using developer1.Core.ServiceContracts;
using AccountServiceClient = developer1.TestConsole.ServiceReference1.Service1Client;
namespace developer1.TestConsole
{
class Program
{
static void Main(string[] args)
{
try
{
AccountServiceClient AccountServiceClient = new AccountServiceClient();
Guid testGuid = Guid.NewGuid();
List<AccountDto> newAccounts = new List<AccountDto>(AccountServiceClient.GenerateMultipleAccounts(2));
Console.WriteLine(testGuid);
CompositeType testDataContract = new CompositeType() { StringValue = "test", BoolValue = true };
testDataContract = AccountServiceClient.GetDataUsingDataContract(testDataContract);
Console.WriteLine(AccountServiceClient.GetData(6));
Console.WriteLine(testDataContract.StringValue);
//foreach (var item in newAccounts)
//{
// Console.WriteLine(item.AccountId);
//}
}
catch(Exception e) {
Console.WriteLine(e);
}
Console.Read();
}
}
}
Data Contract
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace developer1.Core.Dto.Account
{
[DataContract]
public class AccountDto
{
[DataMember]
public Guid AccountId { get; set; }
//get { return this.AccountId; }
//set { this.AccountId = this.AccountId == Guid.Empty ? Guid.NewGuid() : value; }
[DataMember]
public Guid UserId { get; set; }
[DataMember]
public string AccountName { get; set; }
[DataMember]
public string BankName { get; set; }
//get { return this.BankName; }
//set { this.BankName = this.BankName == null ? "Unspecified" : value; }
}
}
ANSWER!!!!!!!
So I have solved this dreaded issue. You must create a WCF Service Library instead of a WCF Service Application. My god that is stupid that the application wont let you split your components outside of the interface.
What I want to do is instead of sending Object { d : "{"FileID":"1213"}" } send "{"FileID":"1213"}"
My current code:
using System;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
[ScriptService]
partial class testing_class : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Session["FileID"] = Request.QueryString["FileID"];
}
public static string returnJSON(object o)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(o);
}
[WebMethod]
[ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
public static string CurrentFile()
{
var d = new { FileID = "123" };
return returnJSON(d);
}
};
Microsoft stack Json serializers are pretty much obsolete and should be avoided at all costs. Instead you should be using (and newer .NET Web stack already is by default) Json.NET implementation.
If you don't have it installed you can do so by running Install-Package Newtonsoft.Json in your NuGet console window. Also make sure you are using Newtonsoft.Json;.
[WebMethod]
[ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
public static string CurrentFile()
{
var d = new { FileID = "123" };
return JsonConvert.SerializeObject(d);
}