Cannot get readable integer from nethereum decoded input data - c#

I'm having trouble with converting solidity's uint256 to readable c# object.
public Transaction DecodeInputData(Transaction tx)
{
EthApiContractService ethApi = new EthApiContractService(null);
var contract = ethApi.GetContract(Abi.Replace(#"\", string.Empty), Address);
var transfer = contract.GetFunction("transfer");
var decodedTx = transfer.DecodeInput(tx.input);
tx.to = (string)decodedTx[0].Result;
tx.value = "0x" + ((BigInteger)decodedTx[1].Result).ToString("x");
return tx;
}
Example Tx: https://etherscan.io/tx/0x622760ad1a0ead8d16641d5888b8c36cb67be5369556f8887499f4ad3e3d1c3d
We must able to convert decodedTx[1].Result variable ( its: {53809663494440740791636285293469688360281260987263635605451211260198698423701}) to 83218945020000000000.
We converting this value to hex to compatibility. But the hex i get is; "0x76f730b400000000000000000000000000000000000000000000000482e51595"
I am using Nethereum library with .net core 2.1

You are trying to decode the smart contract function parameters of a transaction. The smart contract is an ERC20 smart contract, and the function is the Transfer method.
To do so you need to do the following.
Create your Function message in this is scenario the Transfer Function.
Retrieve the transaction
Using the FunctionMessage extension method DecodeTransaction, decode the values of the original Transaction input.
using Nethereum.Web3;
using Nethereum.ABI.FunctionEncoding.Attributes;
using Nethereum.Contracts.CQS;
using Nethereum.Util;
using Nethereum.Web3.Accounts;
using Nethereum.Hex.HexConvertors.Extensions;
using Nethereum.Contracts;
using Nethereum.Contracts.Extensions;
using System;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;
public class GetStartedSmartContracts
{
[Function("transfer", "bool")]
public class TransferFunction : FunctionMessage
{
[Parameter("address", "_to", 1)]
public string To { get; set; }
[Parameter("uint256", "_value", 2)]
public BigInteger TokenAmount { get; set; }
}
public static async Task Main()
{
var url = "https://mainnet.infura.io";
var web3 = new Web3(url);
var txn = await web3.Eth.Transactions.GetTransactionByHash.SendRequestAsync("0x622760ad1a0ead8d16641d5888b8c36cb67be5369556f8887499f4ad3e3d1c3d");
var transfer = new TransferFunction().DecodeTransaction(txn);
Console.WriteLine(transfer.TokenAmount);
//BAT has 18 decimal places the same as Wei
Console.WriteLine(Web3.Convert.FromWei(transfer.TokenAmount));
}
}
You can test this in the http://playground.nethereum.com
Or you can also do, if want to check what function is:
var functionCallDecoder = new FunctionCallDecoder();
if(functionCallDecoder.IsDataForFunction(ABITypedRegistry.GetFunctionABI<TransferFunction>().Sha3Signature, txn.Input)) {
var transfer = new TransferFunction().DecodeInput(txn.Input);
Console.WriteLine(Web3.Convert.FromWei(transfer.TokenAmount));
Console.WriteLine(transfer.To);
}

Related

Writing to a csv after extracting data from a db, cannot modify variable with data

using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
using System.IO;
namespace writingCSV
{
class Program
{
static async Task Main(string[] args)
{
var PatientEmails = await GetPatients();
Type myType = PatientEmails.GetType();
Console.WriteLine(myType);
}
public class PatientSurvey: IDisposable
{
public string Location { get; set; }
public string Email { get; set; }
public void Dispose()
{
throw new NotImplementedException();
}
}
static public async Task<IEnumerable<PatientSurvey>> GetPatients()
{
var connectionString = "SERVER INFORMATION";
using (var cnn = new SqlConnection(connectionString))
{
cnn.Open();
var patientSurveys = await cnn.QueryAsync<PatientSurvey>("STORED PROC NAME",
null,
commandTimeout: 120,
commandType: CommandType.StoredProcedure);
return patientSurveys;
}
}
}
}
I'm attempting to write data to a CSV file from a database. I've successfully connected to the db and extracted the data into a C# object, but I cannot figure out how to modify my data so I can actually write it into the file. The PatientEmails variable has the data within it, but it seems like it's just an instance of the PatientSurvey class.
If I run my variable through a foreach loop, it prints out writingCSV.Program.PatientSurvey for each time it loops.
I don't see any problem. GetPatients returns an IEnumerable of PatientSurvey so indeed looping on the list just print out writingCSV.Program.PatientSurvey.
What would you expect?
If your goal is to print patients email then you should write something like
foreach (var p in patientEmails) {
Console.WriteLine(p.Email);
}

Taking a JSON array with file paths to update the JSON array for date last modified

I currently have an API which I use dapper to connect to a SQL database to find the file path for documents related to a certain ID. The result is returned in JSON format as follows:
[{"DOC-ID": 1, "DOCUMENT_FULL_PATH": "/PATH/FILENAME.DOC"},{"DOC-ID": 2, "DOCUMENT_FULL_PATH": "/PATH/FILENAME2.DOC"}]
I am trying to get my API to deserialize the JSON data then link that too a model (I prefer to not use models but the only solution I found was using JSON DOM which is briefly discussed on MS website but does not provide an example of how to loop through the JSON array so I could not move forward with this example). When I try to deserialize the dapper query result I get the error indicated below (shown at the line item in the code). I am not sure what is triggering this as I would think the QuerySingle could be deserialized with this method. Once this error is fixed I need to check the files last modified date and save that value to the model which I then again need to serialize to send to the front end! I have spent so much time on this so some help would be much appreciated!
[HttpPost]
public ActionResult MainReviewDocuments([FromForm] string ID)
{
//Using FormData on frontend
//checking ID exists on searching in dashboard
if (ID == null || ID.Length == 0)
{
return Ok(new { Result = "Failed" });
}
else
{
//We have parameters here just in case we want to use them
var UserID = HttpContext.User.FindFirst(ClaimTypes.Name).Value;
String query = "select dbo.A2Q_0132W_RR_IDDocumentation_JSON(#ID) as output";
using (var connection = new SqlConnection(connectionString))
{
var json = connection.QuerySingle<string>(query, new { ID = ID});
MainReviewDocuments? mainreviewdocuments = JsonSerializer.Deserialize<MainReviewDocuments>(json); // this line draws an error 'The JSON value could not be converted to Project.Models.MainReviewDocuments. Path: $ | LineNumber: 0 | BytePositionInLine: 1.'
var rootPath = Path.Combine(Directory.GetParent(env.ContentRootPath).ToString(), "Files");
foreach (var document in mainreviewdocuments)
{
filePath = Path.Combine(rootPath, document.DOCUMENT_FULL_PATH);
//Check file system for each file path and set last modified value to model object LAST_MODIFIED. Struggling with this as well
}
return Ok(mainreviewdocuments); // Can I use Ok() method to convert model back to JSON?
}
}
}
In your original call, you need to de-serialize to a List:
MainReviewDocuments? mainreviewdocuments = JsonSerializer.Deserialize<List<MainReviewDocuments>>(json);
and then access your properties are required.
Using Newtonsoft.Json library:
You can de-serialize your JSON string that you receive from your DB into the following class:
public class MainReviewDocuments
{
[JsonProperty("DOC-ID")]
public int DOCID { get; set; }
public string DOCUMENT_FULL_PATH { get; set; }
}
Or you can use dynamic to de-serialize your JSON:
var mainreviewdocuments = JsonSerializer.Deserialize<dynamic>(json);
and then access the properties as shown in the example below.
You can refer to a working example below:
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var myJsonString=#"[{'DOC-ID': 1, 'DOCUMENT_FULL_PATH': '/PATH/FILENAME.DOC'},{'DOC-ID': 2, 'DOCUMENT_FULL_PATH': '/PATH/FILENAME2.DOC'}]";
var mainreviewdocuments =JsonConvert.DeserializeObject<List<MainReviewDocuments>>(myJsonString);
Console.WriteLine("Example using Model: \n");
foreach(var item in mainreviewdocuments)
{
Console.WriteLine(item.DOCID);
Console.WriteLine(item.DOCUMENT_FULL_PATH);
}
Console.WriteLine("\n");
Console.WriteLine("Example using Dynamic: \n");
//Example using dynamic
var mainreviewdocumentsDynamic=JsonConvert.DeserializeObject<dynamic>(myJsonString);
foreach(var item in mainreviewdocumentsDynamic)
{
Console.WriteLine(item["DOC-ID"]);
Console.WriteLine(item["DOCUMENT_FULL_PATH"]);
}
}
}
public class MainReviewDocuments
{
[JsonProperty("DOC-ID")]
public int DOCID { get; set; }
public string DOCUMENT_FULL_PATH { get; set; }
}
Output:
Example using Model:
1
/PATH/FILENAME.DOC
2
/PATH/FILENAME2.DOC
Example using Dynamic:
1
/PATH/FILENAME.DOC
2
/PATH/FILENAME2.DOC
Using System.Text.Json library:
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
public class Program
{
public static void Main()
{
var myJsonString="[{\"DOC-ID\": 1, \"DOCUMENT_FULL_PATH\": \"/PATH/FILENAME.DOC\"},{\"DOC-ID\": 2, \"DOCUMENT_FULL_PATH\": \"/PATH/FILENAME2.DOC\"}]";
var mainreviewdocuments = JsonSerializer.Deserialize<List<MainReviewDocuments>>(myJsonString);
Console.WriteLine("Example using Model: \n");
foreach(var item in mainreviewdocuments)
{
Console.WriteLine(item.DOCID);
Console.WriteLine(item.DOCUMENT_FULL_PATH);
}
Console.WriteLine("\n");
Console.WriteLine("Example using Dynamic: \n");
using (JsonDocument document = JsonDocument.Parse(myJsonString))
{
foreach (JsonElement element in document.RootElement.EnumerateArray())
{
Console.WriteLine(element.GetProperty("DOC-ID"));
Console.WriteLine(element.GetProperty("DOCUMENT_FULL_PATH"));
}
}
}
}
public class MainReviewDocuments
{
[JsonPropertyName("DOC-ID")]
public int DOCID { get; set; }
public string DOCUMENT_FULL_PATH { get; set; }
}
Output:
Example using Model:
1
/PATH/FILENAME.DOC
2
/PATH/FILENAME2.DOC
Example using Dynamic:
1
/PATH/FILENAME.DOC
2
/PATH/FILENAME2.DOC
Working example: https://dotnetfiddle.net/nEjPIK
You can read more on the comparison between the two libraries in this article

'MongoDB.Driver.MongoClient' does not contain a definition for 'GetServer' ...first argument of type 'MongoDB.Driver.MongoClient' could be found

I'm trying to get familiar with writing to MongoDB from c# programs. I've set up my code following suggestions from http://mongodb.github.io/mongo-csharp-driver/1.11/getting_started/
I'm trying to run this program but getting this error "'MongoDB.Driver.MongoClient' does not contain a definition for 'GetServer' and no extension method 'GetServer' accepting a first argument of type 'MongoDB.Driver.MongoClient' could be found". May I get some help?
Thanks in advance,
Tien.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
//Additionally, you will frequently add one or more of these using statements:
//using MongoDB.Driver.Builders; //Error rebuilding when this statement is active: "Using the generic type 'MongoDB.Driver.Builders<TDocument>' requires 1 type arguments
//using MongoDB.Driver.GridFS;
using MongoDB.Driver.Linq;
//using MongoDB.Driver.MongoClient; //Error rebuilding when this statement is active "A using namespace directive can only be applied to namespaces; 'MongoDB.Driver.MongoClient' is a type not a namespace
namespace write2MongoDb
{
public class Entity
{
public ObjectId Id { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
#region Full Sample Program
var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("test");
var collection = database.GetCollection<Entity>("entities");
var entity = new Entity { Name = "Tom" };
collection.Insert(entity);
var id = entity.Id;
var query = Query<Entity>.EQ(e => e.Id, id);
entity = collection.FindOne(query);
entity.Name = "Dick";
collection.Save(entity);
var update = Update<Entity>.Set(e => e.Name, "Harry");
collection.Update(query, update);
collection.Remove(query);
#endregion
Console.ReadKey();
}
}
}
GetServer() has been deprecated, retrieve the database from the client like so:
var client = new MongoClient("mongodb://localhost");
var database = client.GetDatabase("test");
var collection = database.GetCollection<Entity>("entities");

Getting driving distance with Google maps API and SSIS package in C#

UPDATE: Found the Google distancematrix and tried to modify my code accordingly. I am getting an invalid arguments error here:
return new GeoLocation(dstnc, uri.ToString());
}
catch
{
return new GeoLocation(0.0, "https://");
}
Basically, I need to get the driving distance from two known lat/longs. I am using an SSIS package and I found a fantastic tutorial online that comes very close to producing the results I need.
Tutorial: http://www.sqlmusings.com/2011/03/25/geocode-locations-using-google-maps-v3-api-and-ssis/
What they are doing is passing a known street address to Google and reading the lat/long from the returned XML.
What I need to do differently is pass two known lat/longs and read the returned distance.
Example: https://maps.googleapis.com/maps/api/distancematrix/xml?origins=32.1576780,%20-82.9070920&destinations=27.6536997,%20-81.5158944&mode=driving&units=imperial&sensor=false
They use C# which I am not good enough with to know how to make the modification. I took a stab at it anyway and here is what I came up with:
using System;
using System.Collections.Generic;
using System.Text;
//added these
using System.Data;
using System.Net;
using System.Web;
using System.Xml;
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
namespace sqlmusings
{
public interface IGeoLocation
{
string geocodeurl { get; set; }
float distance { get; set; }
}
public struct GeoLocation : IGeoLocation
{
private string _geocodeurl;
private Double _distance;
public GeoLocation(string geocodeurl, Double distance)
{
_geocodeurl = geocodeurl;
_distance = distance;
}
public string geocodeurl
{
get { return _geocodeurl; }
set { _geocodeurl = value; }
}
public Double distance
{
get { return _distance; }
set { _distance = value; }
}
}
public class GeoCode
{
const string _googleUri = "https://maps.googleapis.com/maps/api/distancematrix/xml?origins=";
//sample
//https://maps.googleapis.com/maps/api/distancematrix/xml?origins=32.1576780,-82.9070920&destinations=27.6536997,-81.5158944&mode=driving&units=imperial&sensor=false
private static Uri GetGeoCodeURI(string origins)
{
origins = HttpUtility.UrlEncode(origins);
string uri = String.Format("{0}{1}&sensor=false", _googleUri, origins);
return new Uri(uri);
public static GeoLocation GetCoordinates(string origins)
{
WebClient wc = new WebClient();
Uri uri = GetGeoCodeURI(origins);
try
{
string geoCodeInfo = wc.DownloadString(uri);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(geoCodeInfo);
string status = xmlDoc.DocumentElement.SelectSingleNode("status").InnerText;
double dstnc = 0.0;
XmlNodeList nodeCol = xmlDoc.DocumentElement.SelectNodes("result");
foreach (XmlNode node in nodeCol)
{
dstnc = Convert.ToDouble(node.SelectSingleNode("distance/text").InnerText, System.Globalization.CultureInfo.InvariantCulture);
}
return new GeoLocation(dstnc, uri.ToString());
}
catch
{
return new GeoLocation(0.0, "https://");
}
}
}
}
I added the distance and _distance at the top of the code but Im not sure where to make the change to add a field for my second lat/long.
Just in case, here is the Main.cs (I have not modified it at all):
/* Microsoft SQL Server Integration Services Script Component
* Write scripts using Microsoft Visual C# 2008.
* ScriptMain is the entry point class of the script.*/
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using SC_65a998228f6546ed965116b9f8b76953.csproj;
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
public override void PreExecute()
{
base.PreExecute();
/*
Add your code here for preprocessing or remove if not needed
*/
}
public override void PostExecute()
{
base.PostExecute();
/*
Add your code here for postprocessing or remove if not needed
You can set read/write variables here, for example:
Variables.MyIntVar = 100
*/
}
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
/*
Add your code here
*/
sqlmusings.GeoLocation geolocation = sqlmusings.GeoCode.GetCoordinates(Row.AddressLine1 + "," + Row.City + "," + Row.State + "," + Row.Country);
Row.Latitude = Convert.ToDecimal(geolocation.latitude);
Row.Longitude = Convert.ToDecimal(geolocation.longitude);
Row.GeoCodeURL = geolocation.geocodeurl;
}
}
Just a push in the right direction is all Im asking.
The trick with the String.Format function is that the numbers in braces (e.g. {0} and {1}) are the bits that will be replaced by the arguments you provide in respective order.
What you usually want to do is something like this:
double oLat = 32.1576780, oLng = -82.9070920;
double dLat = 27.6536997, dLng = -81.5158944;
String url = String.Format("https://maps.googleapis.com/maps/api/distancematrix/xml?origins={0},{1}&destinations={2},{3}&mode=driving&sensor=false", oLat, oLng, dLat, dLng);
One thing to keep in mind is that the Maps APIs have Terms & Conditions that require certain things in order to be able to use the API for free. Make sure you read over them, as you may need a commercial license for your use case.

Simple JSON.NET serialization/deserialization example

I've been searching the internet for literally hours trying to find a very simple example of serialization and deserialization with a JSON call in C#. After careful browsing and piecing together, I'd like to call a JSON (POST & GET) function in my webservice (see below).
Here's what I was able to piece together
This would be my service contract (IExecWebservice.svc)
using System.ServiceModel;
using System.ServiceModel.Web;
namespace _27963199
{
[ServiceContract]
public interface IExecFunction
{
[WebGet(UriTemplate = "/{function}/{args}")]
double CalcThis(string function, string args);
}
}
In my main code I parse out the users request URI (IExecFunction.cs)
//user will send variables in REST URI http://myCalcServer/CalcThis/MethodA/10,20
using FunctionLibrary;
using System;
using System.Reflection;
namespace _27963199
{
public class ExecFunctionService : IExecFunction
{
public double CalcThis(string function, string args)
{
Type t = typeof(Functions);
MethodInfo[] libraryFunctions = t.GetMethods(BindingFlags.Static | BindingFlags.Public);
string[] arguments = args.Split(',');
//Missing piece of code where I split the URI for the JSON function that will POST the data object to be be calculated by the DROOLS/Rules Engine and the results passed back to the users web browser
...
}
}
}
Now in my separate function class I'd have something like this (Function.cs)
using System;
using newton.json;
using System.Net.Http;
namespace FunctionLibrary
{
public static class Functions
{
public static double DoMathA(string url, string arg1, string arg2)
{
double d1;
double d2;
if (!double.TryParse(arg1, out d1) || !double.TryParse(arg2, out d2))
{
throw new ArgumentException("Arguments to function 'DoMathA' must be numeric.");
}
//Data Object Format "{'myData':{'Id':'5','var1':'10','var2':'90'}}"
myCalcObject = "{'myData':{'Id':'5', & arg1 & :'10', & arg2 & :'90'}}"
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
DataContractJsonSerializer ser = new DataContractJsonSerializer(data.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject (myCalcObject)
String json = Encoding.UTF8.GetString(ms.ToArray());
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(json);
writer.Close();
}
}
...
//Missing piece of code where I want to return the results of the JSON PUT and GET to the calling webservice
//JSON output string looks like this {"YourResults":{"condition":"YourHairIsOnFire","alertlevel":100,"id":0}}
//return or parse (json) to XLMS on the users browser
}
I need help filling in the blanks so that the request URI is parsed properly to be passed into the JSON function and the reply JSON string be translated back as an xlms on the users browser. Any thoughts?
Update: I tried getting just the JSON section to work as a standalone C# class but I get that "Expected class..." error when I compile it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net.Http;
using System.Net;
using Newtonsoft.Json;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(http://172.16.20.26:8080/myDrools/result);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
DataContractJsonSerializer ser = new DataContractJsonSerializer(data.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject ("{'myData':{'Id':'5','var1':'4.5','var2':'8.7'}}")
String json = Encoding.UTF8.GetString(ms.ToArray());
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(json);
writer.Close();
What Am I doing wrong here? How can I get an XMLS output from this?
You have several bits and pieces. If you glue them together it can work.
Service Interface
Make sure your interface is capable of returning an object that holds the data you expect to return. By making fields nullable you can have variations in how the result looks like.
Notice the ResponseFormat=WebMessageFormat.Json to have json as the returned content type.
[ServiceContract]
public interface IExecFunction
{
[WebGet(UriTemplate = "/{function}/{args}", ResponseFormat=WebMessageFormat.Json)]
[OperationContract]
Result CalcThis(string function, string args);
}
// the result class that actsd as an container
public class Result
{
public Double DoubleResult { get; set; }
public Int32 IntResult { get; set; }
public string Message { get; set; }
}
Service Implementation
The service implementation is bit more involved because it first needs to parse the arguments and convert them to proper types. When that is done it can use reflection to find an appropriate method to call. The returned type is then converted/projected on the Result.
public class ExecFunctionService : IExecFunction
{
// this is a GET /fubar/1,2,3,4
public Result CalcThis(string function, string args)
{
// function=fubar
// args = 1,2,3,4
var allargs = args.Split(',');
// store each argument with their type
var typeList = new List<Tuple<Type, object>>();
// parsr to gind the best match
foreach(var arg in allargs)
{
// convert each argument string
// to a type that is supported
int i;
if (Int32.TryParse(arg, out i))
{
typeList.Add(new Tuple<Type,object>(typeof(Int32), i));
continue;
}
double d;
if (Double.TryParse(arg,
NumberStyles.AllowDecimalPoint,
new CultureInfo("en-us"),
out d))
{
typeList.Add(new Tuple<Type,object>(typeof(Double), d));
continue;
}
// if all fails assume string
typeList.Add(new Tuple<Type,object>(typeof(string), arg));
}
// find and call the correct method
// notice that parameters and their type do matter
// overloads of the same methodname with
// different types is supported
// Functions is the static type with methods to call
var method = typeof(Functions).GetMethod(
function,
BindingFlags.Static| BindingFlags.Public |BindingFlags.InvokeMethod,
null,
typeList.Select(ty => ty.Item1).ToArray(), //all types
null);
var callresult = method.Invoke(
null,
typeList.Select(ty => ty.Item2).ToArray()); // all values
// shape the output in the form you need
var result = new Result();
if(callresult is double)
{
result.DoubleResult = (double) callresult;
}
if (callresult is int)
{
result.IntResult = (int)callresult;
}
if (callresult is string)
{
result.Message = (string)callresult;
}
return result;
}
}
Your Functions to be called
This is the class that holds all your methods that can be called from the service.
// your calc functions go here
public static class Functions
{
public static double DoMathA(double arg1, double arg2)
{
return arg1 / arg2;
}
public static double DoMathB(int number, double factor)
{
return number * factor;
}
public static int DoMathC(string somestring)
{
return somestring.GetHashCode();
}
}
What does it look like?
Calling http://localhost/service1.svc/DoMathC/fubar will return:
{"DoubleResult":0,"IntResult":418978654,"Message":null}
and http://localhost/service1.svc/DoMathA/2.5,3.4 will return:
{"DoubleResult":0.73529411764705888,"IntResult":0,"Message":null}
and http://localhost/service1.svc/DoMathB/4,3.5 will return:
{"DoubleResult":14,"IntResult":0,"Message":null}
Think of it this way: instead of trying to glue together a string, return an object. The service will take care of stringifying it for you.
So, create a class with properties to match the JSON object, and then set your values into those properties, then return the object. Done.
Don't overthink it

Categories