Can't show json data (Xamarin.form) - web-services

I think this is because my json gives me an array, but I don't know how it solved, this is what I did. (I'm new at this)
running in Visual Studio 2019 (xamarin.form) with web services but the url is hidden for security, so don't pay attention in that.
---my-json---
{
"cuentas":[
{
"cuenta":"0500",
"usuario":41
},
{
"cuenta":"0508",
"usuario":6
},
{
"cuenta":"0522",
"usuario":41
},
{
"cuenta":"0532",
"usuario":41
},
null
]
}
---WSClient.cs---
class WSClient
{
public async Task<T> Post<T>(string url, StringContent c)
{
var client = new HttpClient();
var response = await client.PostAsync(url, c);
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(json);
}
}
----Cuenta.cs---
public class Cuenta
{
public string cuenta { get; set; }
public int usuario { get; set; }
}
------MainPage.xaml.cs-----
private async void BtnCall_Clicked(object sender, EventArgs e)
{
WSClient client = new WSClient();
string dato = "";
StringContent content = new StringContent(dato, Encoding.UTF8, "application/json");
var result = await client.Post<Cuenta>("http://www.***", content);
if (result != null) {
lblCuenta.Text = result.cuenta;
lblUsuario.Text = result.cuenta;
}
}
It doesn't show me anything and it doesn't give me any mistakes... any advice?
( I can see the json in the console if I use WriteLine in "WSClient" )

your class should look like this (using json2csharp.com)
public class Cuenta
{
public string cuenta { get; set; }
public int usuario { get; set; }
}
public class RootObject
{
public List<Cuenta> cuentas { get; set; }
}
var result = await client.Post<RootObject>("http://www.***", content);

Related

How to unit test Durable Functions with CallActivityWithRetryAsync

I've read Microsoft documentation on Unit Testing
Unit testing: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-unit-testing
So for example, based on the MS documentation, if this is my orchestrator:
[FunctionName("SagaToTestOrchestrator")]
public static async Task<ShippingPrice> RunOrchestrator(
[OrchestrationTrigger] IDurableOrchestrationContext context)
{
var input = context.GetInput<SagaContext>();
RetryOptions _retryOptions = RetryConfiguration.GetActivityRetryOptions();
// activity to get proper orchestrator for continent for shipping partner
var supplierOrchestratorToRun = await context.CallActivityWithRetryAsync<string>("GetSupplierOrchestratorForContinent", _retryOptions, input.Continent);
// orchestrator to get the price for the shipping address
var priceForShipment =
await context.CallSubOrchestratorAsync<decimal>($"{supplierOrchestratorToRun}Orchestrator", input);
// activity to publish event for Sales / marketing
await context.CallActivityWithRetryAsync("PublishCalculatedPriceActivity", _retryOptions,(input, priceForShipment));
return new ShippingPrice()
{
Shippable = true,
Price = priceForShipment
};
}
[FunctionName("CourierAOrchestrator")]
public static async Task<decimal> CourierAOrchestrator([OrchestrationTrigger] IDurableOrchestrationContext context)
{
return 100;
}
[FunctionName("CourierBOrchestrator")]
public static async Task<decimal> CourierBOrchestrator([OrchestrationTrigger] IDurableOrchestrationContext context)
{
return 120;
}
[FunctionName("IsContinentSupported")]
public static async Task<bool> IsContinentSupported([ActivityTrigger] string continent, ILogger log)
{
var supportedContinents = new List<string>
{
"North America", "South America", "Europe",
};
return supportedContinents.Contains(continent);
}
[FunctionName("GetSupplierOrchestratorForContinent")]
public static async Task<string> GetSupplierOrchestratorForContinent([ActivityTrigger] string continent, ILogger log)
{
var courier = "";
switch (continent)
{
case "South America":
case "North America":
courier = "CourierA";
break;
case "Europe":
courier = "CourierB";
break;
}
return courier;
}
[FunctionName("PublishCalculatedPriceActivity")]
public static async Task PublishCalculatedPriceActivity([ActivityTrigger] (SagaContext context, decimal price) input, ILogger log)
{
log.LogInformation($"{input.context.Continent}: {input.price}");
}
public class ShippingPrice
{
public bool Shippable { get; set; }
public decimal Price { get; set; }
public string Message { get; set; }
}
public class SagaContext
{
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Continent { get; set; }
}
And my test would be something like this:
public async Task CalculatePriceForAmerica()
{
// Arrange / Given
var orchContext = new SagaContext
{
Continent = "North America"
};
var context = new Mock<IDurableOrchestrationContext>();
// mock the get input
context.Setup(m =>
m.GetInput<SagaContext>()).Returns(orchContext);
// set-up mocks for activity
context.Setup(m
=> m.CallActivityWithRetryAsync<string>("GetSupplierOrchestratorForContinent", _retryOptions, It.IsAny<object>()))
.ReturnsAsync("CourierA");
// set-up mocks for suborchstrators
context.Setup(m =>
m.CallSubOrchestratorAsync<decimal>("CourierAOrchestrator", It.IsAny<string>(), It.IsAny<object>()))
.ReturnsAsync(100);
// ACT / When
var price = await SagaToTestOrchestrator.RunOrchestrator(context.Object);
// Assert / Then
Assert.True(price.Shippable);
Assert.Equal(100, price.Price);
}
Here the issue I am facing is
setup mock data for the GetSupplierOrchestratorForContinent Activity , so ideally it should return "CourierA" as output when the actual Orchestrator method is called but it is returning null.

Cloud formation custom resource creation fails

I am trying to create a custom resource which points to a lambda function and then invoke it to generate random Priority or my ELB Listener.
Code for Lambda function is as follows.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace aws_listenser_rule_priority_generator {
public class Function {
public async Task<int> FunctionHandler(FunctionParams input, ILambdaContext context) {
AmazonElasticLoadBalancingV2Client elbV2Client = new AmazonElasticLoadBalancingV2Client(RegionEndpoint.EUWest1);
var describeRulesResponse = await elbV2Client.DescribeRulesAsync(new DescribeRulesRequest {
ListenerArn = input.ListenerArn
});
var priority = 0;
var random = new Random();
do {
priority = random.Next(1, 50000);
}
while(describeRulesResponse.Rules.Exists(r => r.Priority == priority.ToString()));
return priority;
}
}
public class FunctionParams {
public string ListenerArn { get; set; }
}
}
I have tested this lambda on AWS console with the following parameters and it returns successfully.
{
"ListenerArn": "arn:aws:elasticloadbalancing:eu-west-1:706137030892:listener/app/Cumulus/dfcf28e0393cbf77/cdfe928b0285d5f0"
}
But as soon as I try to use this with Cloud Formation. The Custom Resource is stuck at creation in progress.
Resources:
ListenerPriority:
Type: Custom::Number
Properties:
ServiceToken: "arn:aws:lambda:eu-west-1:706137030892:function:GenerateListenerPriority"
ListenerArn: "arn:aws:elasticloadbalancing:eu-west-1:706137030892:listener/app/Cumulus/dfcf28e0393cbf77/cdfe928b0285d5f0"
The issue with the previous approach was the data format. When we are working with the Custom Resources, Cloud Formation sends a request in a specified format and response is expected asynchronously at a specified response URL.
I had to make following updates to the code:
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace aws_listenser_rule_priority_generator
{
public class Function
{
public async Task FunctionHandler(CustomResourceRequest<CustomResourceRequestProperties> crfRequest, ILambdaContext context)
{
var jsonResponse = string.Empty;
if(crfRequest.RequestType.ToUpperInvariant() != "CREATE") {
jsonResponse = JsonSerializer.Serialize(new CustomResourceResponse<object> {
Status = "SUCCESS",
Reason = string.Empty,
PhysicalResourceId = Guid.NewGuid().ToString(),
StackId = crfRequest.StackId,
RequestId = crfRequest.RequestId,
LogicalResourceId = crfRequest.LogicalResourceId,
Data = new {
Dummy = "Dummy"
}
});
}
else {
AmazonElasticLoadBalancingV2Client elbV2Client = new AmazonElasticLoadBalancingV2Client(RegionEndpoint.EUWest1);
var describeRulesResponse = await elbV2Client.DescribeRulesAsync(new DescribeRulesRequest {
ListenerArn = crfRequest.ResourceProperties.ListenerArn
});
var priority = 0;
var random = new Random();
do {
priority = random.Next(1, 50000);
}
while(describeRulesResponse.Rules.Exists(r => r.Priority == priority.ToString()));
jsonResponse = JsonSerializer.Serialize(new CustomResourceResponse<object> {
Status = "SUCCESS",
Reason = string.Empty,
PhysicalResourceId = Guid.NewGuid().ToString(),
StackId = crfRequest.StackId,
RequestId = crfRequest.RequestId,
LogicalResourceId = crfRequest.LogicalResourceId,
Data = new {
Priority = priority
}
});
}
var byteArray = Encoding.UTF8.GetBytes(jsonResponse);
var webRequest = WebRequest.Create(crfRequest.ResponseURL) as HttpWebRequest;
webRequest.Method = "PUT";
webRequest.ContentType = string.Empty;
webRequest.ContentLength = byteArray.Length;
using(Stream datastream = webRequest.GetRequestStream()) {
await datastream.WriteAsync(byteArray, 0, byteArray.Length);
}
await webRequest.GetResponseAsync();
}
}
public class CustomResourceRequest<T> where T : ICustomResourceRequestProperties {
public string RequestType { get; set; }
public string ResponseURL { get; set; }
public string StackId { get; set; }
public string RequestId { get; set; }
public string ResourceType { get; set; }
public string LogicalResourceId{ get; set; }
public string PhysicalResourceId { get; set; }
public T ResourceProperties { get; set; }
public T OldResourceProperties { get; set; }
}
public class CustomResourceResponse<T> {
public string Status { get; set; }
public string Reason { get; set; }
public string PhysicalResourceId { get; set; }
public string StackId { get; set; }
public string RequestId { get; set; }
public string LogicalResourceId { get; set; }
public bool NoEcho { get; set; }
public T Data { get; set; }
}
public interface ICustomResourceRequestProperties {
public string ServiceToken { get; set; }
}
public class CustomResourceRequestProperties : ICustomResourceRequestProperties
{
string ICustomResourceRequestProperties.ServiceToken { get; set; }
public string ListenerArn { get; set; }
}
}
The above code expects everything to work without any issues and there are no try catch blocks. Best practice would be to have try catch blocks and send a failure response.
Following URLs can be referred for more details:
Custom resources
Custom resource request objects
Custom resource response objects
Using AWS Lambda with AWS CloudFormation

consuming asmx webservice in xamarin forms

I am working on a login page in Xamarin forms and I need to consume an asmx webservice in order to connect to the sql server. I used this example: https://github.com/fabiosilvalima/FSL.ConsummingAsmxServicesInXamarinForms, and tried to apply the same steps for my app. but I got an error.
here's my code:
ILogin.cs:
namespace App33.Models
{
public interface ILogin
{
string Error { get; set; }
bool ValidUser { get; set; }
}
}
ILoginSoapService.cs
public interface ILoginSoapService
{
Task<List<ILogin>> Login(string namee, string passs);
}
in App.xaml.cs
private static ILoginSoapService _loginSoapService;
public static ILoginSoapService LoginSoapService
{
get
{
if (_loginSoapService == null)
{
_loginSoapService = DependencyService.Get<ILoginSoapService>();
}
return _loginSoapService;
}
Main.xaml.cs
public MainPage()
{
InitializeComponent();
}
async void OnButtonClicked(object sender, EventArgs e)
{
var entr_usrname = this.FindByName<Entry>("username");
string usrname = entr_usrname.Text;
var entr_pass = this.FindByName<Entry>("Password");
string pass = entr_pass.Text;
var state = await App.LoginSoapService.Login(usrname,pass);
if (state[0].ValidUser == true)
{
await DisplayAlert("Alert", "You have been alerted", "OK");
}
}
this is for the portable app. my webservice is added to the web reference as LoginWs. it has the following codes:
Result.cs:
public class Result
{
public string Error { get; set; }
public bool ValidUser { get; set; }
}
WebService1.asmx.cs:
[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 WebService1 : System.Web.Services.WebService
{
[WebMethod]
public Result Login(string userName, string userPass)
{
SqlConnection conn=new SqlConnection (new DBConnection().ConnectionString);
Result result = new Result();
try
{
SqlCommand cmd = new SqlCommand("SELECT userName, password FROM users where CONVERT(VARCHAR, username)=#username and CONVERT(VARCHAR, password)=#password");
cmd.Parameters.AddWithValue("username", userName);
cmd.Parameters.AddWithValue("password", userPass);
cmd.Connection = conn;
if (conn.State==System.Data.ConnectionState.Closed)
{
conn.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
result.ValidUser = true;
return result;
}
else
{
result.ValidUser = false;
}
}
catch(Exception ex)
{
result.Error = ex.ToString();
}
finally
{
conn.Close();
}
return result;
}
}
}
now in App.Android:
Result.cs
namespace App33.Droid.LoginWs
{
public partial class Result : ILogin
{
}
}
LoginSoapService.cs
[assembly: Dependency(typeof(App33.Droid.LoginSoapService))]
namespace App33.Droid
{
public sealed class LoginSoapService :ILoginSoapService
{
LoginWs.WebService1 service;
public LoginSoapService()
{
service = new LoginWs.WebService1()
{
// Url = "http://codefinal.com/FSL.ConsummingAsmxServicesInXamarinForms/Customers.asmx" //remote server
Url = "http://192.168.0.106/site2/WebService1.asmx" //localserver - mobile does not understand "localhost", just that ip address
};
}
public async Task<List<ILogin>> Login( string namee,string pass)
{
return await Task.Run(() =>
{
var result = service.Login(namee,pass);
return new List<ILogin>(result);
});
}
}
}
the error i'm getting is in this line:return new List(result);. it says: Error CS1503 Argument 1: cannot convert from 'App33.Droid.LoginWs.Result' to 'int'. I can't figure out what the peoblem is. sorry for the long question. any help is appreciated.

Xamarin web services Unit test

Can you please suggest how to write unit test for web services in xamarin forms, I am getting error to on running
[TestFixture()]
public class LeadRepositoryTest
{
private Mock<ILeadWebService> mockLeadWebService { get; set; }
private Mock<ILeadDatabaseService> mockLeadDatabaseService { get; set; }
private LeadService leadRepository { get; set; }
public LeadRepositoryTest()
{
var repository = new MockRepository(MockBehavior.Default) { DefaultValue = DefaultValue.Empty };
mockLeadWebService = repository.Create<ILeadWebService>().As<ILeadWebService>();
mockLeadDatabaseService = repository.Create<ILeadDatabaseService>().As<ILeadDatabaseService>();
mockLeadWebService.Setup(x => x.GetNormalLeads(CommonMockData.GetLeadRequestParams())).Returns(Task.FromResult(OperationResult.CreateSuccessResult(new GetLeadsApiResponseDTO())));
leadRepository = new LeadService(mockLeadDatabaseService.Object, mockLeadWebService.Object, null, null);
}
[Test()]
public async void GetNormalLeads_WebServiceIsNotNull()
{
//Arrange
var parameters = new LeadRequestParams()
{
Offset = 0,
Limit = 20,
PageName = "Today",
};
//Act
var operationResult = await leadRepository.GetNormalLeads(parameters);
//Assert
Assert.IsNotNull(operationResult?.Data);
}
},
I think what you really need is:
var mockLeadRepository = new Mock<ILeadService>();
mockLeadRepository.Setup(x => x.GetNormalLeads(It.IsAny<Object>())).Returns(Task.FromResult(OperationResult.CreateSuccessResult(new GetLeadsApiResponseDTO())));
leadRepository = mockLeadRepository.Object;

Iterating through SharePoint 2013 REST API List Items

I am writing a Provider Hosted APP using SP 2013 and I have a data layer which uses REST to CRUD on sharepoint lists. Now I got the List items in JSON format but I am not able to iterate through the list data can you please help in doing that? (is there any class for List Items which I can deserialize into?)
This is the code
public JToken GetListData(string webUrl, string userName, SecureString password, string listTitle)
{
using (var client = new WebClient())
{
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Credentials = new SharePointOnlineCredentials(userName, password);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json;odata=verbose");
client.Headers.Add(HttpRequestHeader.Accept, "application/json;odata=verbose");
var endpointUri = new Uri(new Uri(webUrl), string.Format("/sites/DTF/_api/web/lists/getbytitle('{0}')/Items", listTitle));
var result = client.DownloadString(endpointUri);
var t = JToken.Parse(result);
return t["d"];
}
}
You need to use the DataContractJsonSerializer class to deserialize the data as is demonstrated here:
http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET
To make this work though you have to create classes that match the structure of the Json. The easiest way to do this copying a raw Json response into a tool which will generate the classes like this one:
http://json2csharp.com/
The actual classes you will need to generate varies based on the structure of the data you are getting in your REST response. Here is an example I created that demonstrates making a request, parsing the Json Response and downloading a file based on the result:
public class JsonHelper
{
/// JSON Serialization
public static string JsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
/// JSON Deserialization
public static T JsonDeserialize<T>(string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}
}
//Custom Json Classes
public class RootObject
{
public D d { get; set; }
}
public class D
{
public GetContextWebInformation GetContextWebInformation { get; set; }
public List<Result> results { get; set; }
}
public class GetContextWebInformation
{
public int FormDigestTimeoutSeconds { get; set; }
public string FormDigestValue { get; set; }
public string LibraryVersion { get; set; }
public string SiteFullUrl { get; set; }
public string WebFullUrl { get; set; }
}
public class Result
{
public ContentType ContentType { get; set; }
public string EncodedAbsUrl { get; set; }
public string FileLeafRef { get; set; }
public Folder Folder { get; set; }
public int FileSystemObjectType { get; set; }
public int Id { get; set; }
public string ContentTypeId { get; set; }
public string Title { get; set; }
public int? ImageWidth { get; set; }
public int? ImageHeight { get; set; }
public string ImageCreateDate { get; set; }
public object Description { get; set; }
public object Keywords { get; set; }
public string OData__dlc_DocId { get; set; }
public int ID { get; set; }
public string Created { get; set; }
public int AuthorId { get; set; }
public string Modified { get; set; }
public int EditorId { get; set; }
public object OData__CopySource { get; set; }
public int? CheckoutUserId { get; set; }
public string OData__UIVersionString { get; set; }
public string GUID { get; set; }
}
//SharePoint Calls
class Program
{
static void Main()
{
string url = "https://sharepoint.wilsonconst.com/";
string filename = "2010-07-23 13.32.22.jpg";
string digest = "";
HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
string cmd = "_api/contextinfo";
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json");
client.DefaultRequestHeaders.Add("ContentLength", "0");
StringContent httpContent = new StringContent("");
HttpResponseMessage response = client.PostAsync(cmd, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
RootObject sp = JsonHelper.JsonDeserialize<RootObject>(content);
digest = sp.d.GetContextWebInformation.FormDigestValue;
}
client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
client.DefaultRequestHeaders.Add("X-HTTP-Method", "GET");
string uri = "_api/web/lists/GetByTitle('Wilson Pictures')/Items?$select=ID,FileLeafRef,EncodedAbsUrl&$filter=FileLeafRef eq '" + filename + "'";
HttpResponseMessage response2 = client.GetAsync(uri).Result;
response2.EnsureSuccessStatusCode();
if (response2.IsSuccessStatusCode)
{
string listItems = response2.Content.ReadAsStringAsync().Result;
RootObject sp = JsonHelper.JsonDeserialize<RootObject>(listItems);
foreach (Result result in sp.d.results)
{
MemoryStream stream = (MemoryStream)client.GetAsync(result.EncodedAbsUrl).Result.Content.ReadAsStreamAsync().Result;
using(FileStream fileStream = System.IO.File.Create(#"C:\" + result.FileLeafRef))
{
stream.WriteTo(fileStream);
}
}
}
else
{
var content = response.Content.ReadAsStringAsync();
}
}
This seems like a lot of complexity, but really it makes working with Json objects quite easy and takes only moments to setup before you can start calling your custom objects to easily manipulate the data.
Assuming that you want to retrieve data from SharePoint Online the following example demonstrates how to consume SharePoint REST Interface via WebClient Class:
using (var client = new SPRestClient(webUri.ToString()))
{
client.Credentials = GetCredentials(webUri,userName,password);
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
var data = client.GetJson("/_api/lists/getbytitle('Tasks')/items"); //get list items
//print list item's title
foreach (var item in data["d"]["results"])
{
Console.WriteLine(item["Title"]);
}
}
where
public static SharePointOnlineCredentials GetCredentials(Uri webUri, string userName, string password)
{
var securePassword = new SecureString();
foreach (var ch in password) securePassword.AppendChar(ch);
return new SharePointOnlineCredentials(userName, securePassword);
}
and
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace SharePoint.Client
{
public class SPRestClient : WebClient
{
public SPRestClient(string webUri)
{
BaseAddress = webUri;
FormatType = JsonFormatType.Verbose;
}
public JObject GetJson(string requestUri)
{
return ExecuteJson(requestUri, HttpMethod.Get, null, default(string));
}
public JObject ExecuteJson<T>(string requestUri, HttpMethod method, IDictionary<string, string> headers, T data)
{
string result;
var uri = BaseAddress + requestUri;
if (headers != null)
{
foreach (var key in headers.Keys)
{
Headers.Add(key, headers[key]);
}
}
EnsureRequest(method);
switch (method.Method)
{
case "GET":
result = DownloadString(uri);
break;
case "POST":
if (data != null)
{
var payload = JsonConvert.SerializeObject(data);
result = UploadString(uri, method.Method, payload);
}
else
{
result = UploadString(uri, method.Method);
}
break;
default:
throw new NotSupportedException(string.Format("Method {0} is not supported", method.Method));
}
return JObject.Parse(result);
}
private void EnsureRequest(HttpMethod method)
{
var mapping = new Dictionary<JsonFormatType, string>();
mapping[JsonFormatType.Verbose] = "application/json;odata=verbose";
mapping[JsonFormatType.MinimalMetadata] = "application/json; odata=minimalmetadata";
mapping[JsonFormatType.NoMetadata] = "application/json; odata=nometadata";
Headers.Add(HttpRequestHeader.ContentType, mapping[FormatType]);
Headers.Add(HttpRequestHeader.Accept, mapping[FormatType]);
if (method == HttpMethod.Post)
{
Headers.Add("X-RequestDigest", RequestFormDigest());
}
}
private string RequestFormDigest()
{
var endpointUrl = string.Format("{0}/_api/contextinfo", BaseAddress);
var result = UploadString(endpointUrl, "Post");
var contentJson = JObject.Parse(result);
return contentJson["FormDigestValue"].ToString();
}
public JsonFormatType FormatType { get; set; }
}
public enum JsonFormatType
{
Verbose,
MinimalMetadata,
NoMetadata
}
}
SPRestClient.cs