Pass class name to method - c#

I am writing a Windows Phone 8.1 App (WINRT). I have to call HTTPHandlerMethod method accepting three parameters. I pass Server API address as string, JsonString to be send to server as string, and also I need to send class name to HTTPHandlerMethod also as third parameter. How to send class name? I actually need to use class name inside this method in JSON DeSerializing:
JsonConvert.DeserializeObject(JSonData_Recieved,CLASS NAME HERE);
public async void HTTPHandlerMethod(string AddressPath,
string JSonData_ToSend, **WHAT THIRD PARAMETER TO WRITE HERE??**)
{
Object resObject = null;
HttpBaseProtocolFilter HttpBaseProtocolFilterObject = new HttpBaseProtocolFilter();
HttpClient HttpClientObject = new HttpClient(HttpBaseProtocolFilterObject);
string CompleteAddress = singletonInstance.APIServer + AddressPath;
Uri UriObject = new Uri(CompleteAddress);
HttpRequestMessage HttpRequestMessageObject =
new HttpRequestMessage(HttpMethod.Post, UriObject);
HttpRequestMessageObject.Content = new HttpStringContent(JSonData_ToSend,
Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
try
{
HttpResponseMessage HttpResponseMessageObject =
await HttpClientObject.SendRequestAsync(HttpRequestMessageObject,
HttpCompletionOption.ResponseContentRead);
if (HttpResponseMessageObject.IsSuccessStatusCode) //If 2xx success is recieved
{
string JSonData_Recieved =
await HttpResponseMessageObject.Content.ReadAsStringAsync();
resObject = JsonConvert.DeserializeObject(JSonData_Recieved,resType);
}
}
catch { }
}
}
What modifications should I do to this HTTPHandlerMethod method? and how to call it then?

public async void HTTPHandlerMethod(string AddressPath,
string JSonData_ToSend, Type classname)
{
}

Related

How to post a string array using Flurl?

In UI, the input type for SourceOfWealthOrIncome is a checkbox. In the front-end Razor page, I am using Flurl to issue a POST request.
var baseUrl = configuration.GetSection("xxx").GetValue<string>("Url");
string endPoint = "/Api/test/";
string url = string.Format("{0}{1}{2}", baseUrl, endPoint, ecddClientId);
var response = await url.SetQueryParams(new { id = ecddClientId, dealerCode })
.PostMultipartAsync(mp =>
{
mp = mp.AddString("SourceOfWealthOrIncome", postData.SourceOfWealthOrIncome);
foreach (var doc in postData.SupportingDocs)
{
mp = mp.AddFile("SupportingDocs", doc.FileContent, doc.FileName);
}
});
Troubleshoot: If I changed from SourceOfWealthOrIncome[] to SourceOfWealthOrIncome, I can see the values of the checkbox for example "value1, value2". But I can't change the endpoint code. This is the code for endpoint in C# in .NET Framework 4.x.
[HttpPost]
public async Task<IHttpActionResult> PutEnhancedCdd(int id, string dealerCode)
{
string root = Path.GetTempPath();
var provider = new MultipartFormDataStreamProvider(root);
await Request.Content.ReadAsMultipartAsync(provider);
var sourceOfWealthOrIncome = provider.FormData["SourceOfWealthOrIncome[]"];
return Ok();
}
How do I change my front-end code using Flurl so that I can send a string object over to this current endpoint?

How can I pass an object (class) to Rest Service

In my REST Service I have the following:
AssetController:
// GET: <AssetController>
[HttpGet("{companyID}/{machineName}")]
public Asset Get(int companyID, string machineName)
{
Database db = new Database(configuration.ConnectionString);
//DataSet ds = db.executeFunctionSelect("fngetallassets2()");
DataSet ds = db.executeViewSelect("tblasset where LOWER(name) = '" + machineName.ToLower() + "'");
//DataSet ds = db.executeDataSetProc("getallassets", null);
DataTable table = ds.Tables[0];
DataRow row = table.Rows[0];
Asset asset = new Asset
{
ID = int.Parse(row["ID"].ToString()),
CompanyID = int.Parse(row["Company_ID"].ToString()),
Name = row["Name"].ToString(),
IPAddress = row["IP_Address"].ToString(),
CreateDate = DateTime.Parse(row["Create_Date"].ToString()),
IsActive = bool.Parse(row["Is_Active"].ToString())
};
return asset;
}
This works fine... Its the PUT that I need help with
// PUT /<AssetController>/5
// Insert record into the database
[HttpPut("{asset}")]
public void Put([FromBody] string asset)
{
Database db = new Database(configuration.ConnectionString);
db.executeNonQuery("sp_AssetInsert", null);
}
Here I am trying to pass (somehow) the same asset class
In the calling windows forms I use this way to call the PUT Method:
public void InsertAsset(Asset asset)
{
ArrayList parameters = new ArrayList
{
asset.Name,
asset.IPAddress
};
RestClient client = new RestClient("https://localhost:5001/Asset/");
RestRequest request = new RestRequest(Method.PUT);
request.AddJsonBody(asset);
IRestResponse<List<string>> response = client.Execute<List<string>>(request);
if (response.StatusCode == HttpStatusCode.OK)
{
}
I get an error on Response.StatusCode = unsupportedmedia or something like this.
I need to know how to serialize or somehow pass either the class or the JSON string of it or whatever...
Can someone please help me figure out how to call the PUT methods as I have dozens of these to do.
Here is the calling and receiving code used to make this work.
calling:
RestClient client = new RestClient("https://localhost:5001/Asset/");
RestRequest request = new RestRequest(Method.PUT);
request.AddJsonBody(asset); <-- Asset is a class object
RestResponse response = (RestResponse)client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
}
Receiving Code:
// PUT /<AssetController>/5
// Insert record into the database
[HttpPut]
public void Put([FromBody] Asset asset)
{
Database db = new Database(configuration.ConnectionString);
db.executeNonQuery("sp_AssetInsert", null);
}
I needed to change the [FromBody] string asset to [FromBody] Asset asset
There are several ways to pass parameters:
as url route i.e. https://localhost:5001/Asset/42/MyCompanyName
as url parameter http:// localhost:5001/Asset?companyID=42&machineName=companyname
in body, typically as a json serialized object
when you specify the route in [HttpPut("{paramaters}")] you are specifying option 1. You can use FromBody and FromUrl attributes on the parameter to control this. Simple parameters like numbers and string would typically be part of the URL, while complex objects like Asset will probably be easier to pass in the body.
See also
restsharp parameter posting
asp.net parameter binding

C# How can I call an http post method and get back the results

I have a method that is a http Post I call that method and pass along 2 parameter then it returns 2 parameters back . I have it working the traditional way but now I would like to get it working using RestSharp .I would like to call that method now using RestSharp but I am having no luck . This below works
public static void Main() {
var getController = new AccessController();
var merchSales = getController.Merchandise("Bags",5);
var status = merchSales.Status;
var items = merchSales.ItemsCount;
if (status.sold == status)
{
console("It's Sold");
}
else if (status.available == status)
{
console("It's Available");
}
}
I am now trying to do that using RestSharp http://restsharp.org/ . However How can I get back the return value of the Enum to do an If statement check like I did above ? For instance in the code above the merchSales.Status is an enum that will return either Available or Sold . This is my code below it's meant to be a HTTP call
public static void Main() {
var client = new RestClient ("http://localhost:1275/api/");
var request = new RestRequest("Resource/{id}", Method.POST);
request.AddParameter("Item", "Bags");
request.AddParameter("Count", 5);
RestResponse response = client.Execute(request);
client.ExecuteAsync(request, data => {
Console.WriteLine(data.Content);
});
}

client.GetAsync doesn't refresh my data

I develop au Universal App using MVVM-Light.
On a page, there is a list of comments coming from a WebService. If the current user is the author of a comment, I show a FlyoutMenu allowing him to "Edit" or "Delete" its comment. There is also a AppBarButton for adding a new comment:
My problem is that the comments are never refreshed after the first load of this page...
I use a "LoadComments()" method in the ViewModel that allows me to get the comments when I arrive on the page, but also after editing, deleted or added an item:
private async void LoadComments()
{
List<Comment> commentsWS = await WebServiceGetCommentList();
if (commentsWS != null)
Comments = new ObservableCollection<Commentaire>(commentsWS);
}
This method so calls another method "WebServiceGetCommentList()" that prepares the call to the WebService, in the same ViewModel:
private async Task<List<Comment>> WebServiceGetCommentList()
{
// Parameters
List<KeyValuePair<string, string>> parametres = new List<KeyValuePair<string, string>>();
parametres.Add(new KeyValuePair<string, string>("option", _currentUserAccount.option));
parametres.Add(new KeyValuePair<string, string>("id_article", Article.id_article.ToString()));
// Call WebService and deserialize
Exception custEx = null;
try
{
List<Comment> comments = await WebServices.GetCommentList(_currentUserAccount.url, parametres, "");
return comments;
}
// Exceptions
catch (Exception e)
{
...
}
return null;
}
I then go in the "GetComments()" method on the "WebServices" class:
public static async Task<List<Comment>> GetCommentList(String url, List<KeyValuePair<String, String>> parametres, String protocol)
{
// Call WebService and deserialize
var response = await JSONParser.getJSONFromUrl(url, parametres, "");
List<Comment> comments = new List<Comment>();
WsResponse wsResponse = ManageWsReponse(response, Constants.WebServiceTask.GetCommentList.Value);
try
{
WsResponseResult wsResponseResult = JsonConvert.DeserializeObject<WsResponseResult>(wsResponse.data.ToString());
comments = JsonConvert.DeserializeObject<List<Comment>>(wsResponseResult.result.ToString());
return comments;
}
catch (Exception e)
{
throw new DeserializeException("Deserialize exception", e, DateTime.Now, "Comment");
}
}
This method calls the "getJSONFromUrl()" method in the "JSONParser" class that launches the "client.GetAsync()":
public static async Task<string> getJSONFromUrl(String url, List<KeyValuePair<String, String>> parameters, String protocol)
{
var client = new HttpClient();
// Preparing URI
string sParameters = null;
int i = 1;
foreach (var param in parameters)
{
sParameters += param.Key + "=" + param.Value;
sParameters += i != parameters.Count ? "&" : string.Empty;
i++;
}
var uri = new Uri(url + "?" + sParameters);
// Calls the WebService
var response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead);
// Code and results
var statusCode = response.StatusCode;
// EnsureSuccessStatusCode throws exception if not HTTP 200
response.EnsureSuccessStatusCode();
// responseText
var responseText = await response.Content.ReadAsStringAsync();
return responseText;
}
I can add, delete or edit a comment with success, but when I'm back to this method "LoadComments()", the changes are not taken into account, and I get the same list than at the first call...
I also placed breakpoints in the "GetJSONFromURL()" method and I don't see the added, deleted or edited comments in the response var.
In the same time, if I copy the URI in a brower, for calling the same WebService with the same parameters, the changes are taken into account.
=> I think so there is a caching on client.GetAsync(), but I don't see how to desactive it, or force it to refresh datas...
I tried this solution httpclient-caching that doesn't work for me.
I think so that there is cache managing cause when I
That's the platform caching. I haven't had any success with the Cache-Control headers, the most reliable way to address the issue is to make sure the request is different.
Add an additional parameter - a timestamp. As the request is different, the platform cannot used the cached response.
parametres.Add(new KeyValuePair<string, string>("mytmstmp", DateTime.Now.Ticks);
Or: Use an additional header that allows for a date. I've used:
"If-Modified-Since", DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)

Office 365 REST API - Adding a Contact with JSON in C#

I am trying to use the Office API to sync contacts from a few different sources. I have been having a problem trying to make a POST request with my JSON object to create a new contact. I have been looking at the MSDN pages but I feel like I should clarify I’m relatively new to C#, this is my first time trying to use REST protocols, and async methods in C#.
I have my code below, I tried to create a class that will add a new contact with a hard coded JSON string. I have tried a few various ways of trying to complete this request. Every request I have attempted gives me a 401 or 400 Error. I left a couple lines that I felt were closest to the solution but if those are not on the right track I have no problem trying something else. There is also a function that I believe could be useful but I couldn’t really find documentation on how to use it:
await client.Me.Contacts.AddContactAsync();
Again I said I am pretty new to this so if there is a way to create an IContact item from the JSON and use the above method or to just pass the JSON directly either would be extremely useful. Even links to documentation that could be useful I would love to see. I’m a pretty stuck on this problem I’ve never posted a question before but I’m stumped on this.
Below is the documentation for the Contacts API maybe it will make more sense to you guys than me.
http://msdn.microsoft.com/en-us/library/office/dn792115(v=office.15).aspx
If anybody can figure out how to make a post request from that JSON it will be much appreciated.
using Microsoft.Office365.Exchange;
using Microsoft.Office365.OAuth;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows;
using System.Net.Http;
using System.Net.Http.Headers;
namespace ContactSynchronization
{
class OfficeAPIWrite
{
private static string odata = "#odata.type";
private static string type = "#Microsoft.Exchange.Services.OData.Model.Contact";
const string ServiceResourceId = "https://outlook.office365.com";
static readonly Uri ServiceEndpointUri = new Uri("https://outlook.office365.com/ews/odata/Me/Contacts");
static string _lastLoggedInUser;
static DiscoveryContext _discoveryContext;
public static async Task OfficeWrite()
{
try
{
var client = await EnsureClientCreated();
string json = new JavaScriptSerializer().Serialize(new
{
odata = type,
GivenName = "Mara",
Surname = "Whitley",
EmailAddress1 = "mara#fabrikam.com",
BusinessPhone1 = "425-555-1313",
Birthday = "1974-07-22T07:00:00Z"
});
try
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, ServiceEndpointUri);
request.Content = new StringContent(json);
request.Headers.Add("Accept", "application/json;odata=minimalmetadata");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
catch (System.Net.WebException e)
{
MessageBox.Show(e.ToString());
}
}
catch (Microsoft.Office365.OAuth.AuthenticationFailedException)
{
MessageBox.Show("Authentication Failed Exception was thrown");
}
}
public static async Task<ExchangeClient> EnsureClientCreated()
{
if (_discoveryContext == null)
{
_discoveryContext = await DiscoveryContext.CreateAsync();
}
var dcr = await _discoveryContext.DiscoverResourceAsync(ServiceResourceId);
_lastLoggedInUser = dcr.UserId;
return new ExchangeClient(ServiceEndpointUri, async () =>
{
return (await _discoveryContext.AuthenticationContext.AcquireTokenSilentAsync(ServiceResourceId, _discoveryContext.AppIdentity.ClientId, new Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier(dcr.UserId, Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifierType.UniqueId))).AccessToken;
});
}
public static async Task SignOut()
{
if (string.IsNullOrEmpty(_lastLoggedInUser))
{
return;
}
if (_discoveryContext == null)
{
_discoveryContext = await DiscoveryContext.CreateAsync();
}
await _discoveryContext.LogoutAsync(_lastLoggedInUser);
}
}
}
Well I guess I figured out a work around. This uses a ContactObject that I created and newtonsoft's JSON serializer. I was hoping to see an example of the microsoft ExchangeClient in action, the only reason I am posting this is to help others that might have similar issues posting to the office API, the below code will run successfully. I'm still looking though if anybody can show me the correct way to use the ExchangeClient functions.
// your request must include these, and a given name,
// everything else is optional
private const string odata = "#odata.type";
private const string type = "#Microsoft.Exchange.Services.OData.Model.Contact";
public static async Task CreateContact(ContactObject officeContact, string userEmail, string userPassword)
{
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, new Uri("https://outlook.office365.com/ews/odata/Me/Contacts"));
// Add the Authorization header with the basic login credentials.
var auth = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(userEmail + ":" + userPassword));
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Authorization", auth);
var createResponse = new JObject();
createResponse[odata] = type; // this needs to be here for this to work
if (!String.IsNullOrEmpty(officeContact.officeDisplayName)) createResponse["DisplayName"] = officeContact.officeDisplayName;
if (!String.IsNullOrEmpty(officeContact.officeGivenName)) createResponse["GivenName"] = officeContact.officeGivenName;
if (!String.IsNullOrEmpty(officeContact.officeMiddleName)) createResponse["MiddleName"] = officeContact.officeMiddleName;
if (!String.IsNullOrEmpty(officeContact.officeNickName)) createResponse["NickName"] = officeContact.officeNickName;
if (!String.IsNullOrEmpty(officeContact.officeSurname)) createResponse["Surname"] = officeContact.officeSurname;
if (!String.IsNullOrEmpty(officeContact.officeEmailAddress1)) createResponse["EmailAddress1"] = officeContact.officeEmailAddress1;
if (!String.IsNullOrEmpty(officeContact.officeEmailAddress2)) createResponse["EmailAddress2"] = officeContact.officeEmailAddress2;
if (!String.IsNullOrEmpty(officeContact.officeEmailAddress3)) createResponse["EmailAddress3"] = officeContact.officeEmailAddress3;
if (!String.IsNullOrEmpty(officeContact.officeHomePhone1)) createResponse["HomePhone1"] = officeContact.officeHomePhone1;
if (!String.IsNullOrEmpty(officeContact.officeHomePhone2)) createResponse["HomePhone2"] = officeContact.officeHomePhone2;
if (!String.IsNullOrEmpty(officeContact.officeBusinessPhone1)) createResponse["BusinessPhone1"] = officeContact.officeBusinessPhone1;
if (!String.IsNullOrEmpty(officeContact.officeBusinessPhone2)) createResponse["BusinessPhone2"] = officeContact.officeBusinessPhone2;
if (!String.IsNullOrEmpty(officeContact.officeMobilePhone1)) createResponse["MobilePhone1"] = officeContact.officeMobilePhone1;
if (!String.IsNullOrEmpty(officeContact.officeOtherPhone)) createResponse["OtherPhone"] = officeContact.officeOtherPhone;
if (!String.IsNullOrEmpty(officeContact.officeId)) createResponse["Id"] = officeContact.officeId;
if (!String.IsNullOrEmpty(officeContact.officeCompanyName)) createResponse["CompanyName"] = officeContact.officeCompanyName;
request.Content = new StringContent(JsonConvert.SerializeObject(createResponse));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.SendAsync(request);
try
{
response.EnsureSuccessStatusCode();
}
catch (System.Net.WebException)
{
MessageBox.Show("BAD REQUEST");
}
}

Categories

Resources