How to send HTTP POST request with HTTP header for Xamarin PCL to web service? - rest

I am using a PCL project.
I need to send a HTTP POST request with some parameters as well as HTTP header to the web service. The web-service will then return json data back to my client.
How should I do that ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
public interface IJsonHelper
{
Task<IEnumerable<OverallOutlet>> GetData();
}
public class JsonHelper : IJsonHelper
{
string url = "http://someurl.com";
public async Task<IEnumerable<OverallOutlet>> GetData()
{
var client = new HttpClient();
// How to add http header (for example, Key : token, Value : 123456) ?
var post_data = new FormUrlEncodedContent( new [] {
new KeyValuePair<string, string>("username", ""),
new KeyValuePair<string, string>("password", "")
});
var result = await client.PostAsync(url, post_data);
return JsonConvert.DeserializeObject<IEnumerable<OverallOutlet>>(result.ToString());
}
}

Call client.DefaultRequestHeaders.Add("Key", "value"); in order to set the request header.
EDIT:
Or you create a HttpRequestMessage and add the headers. You can send the message via client.SendAsync. Look here http://massivescale.com/custom-headers-with-httpclient/

Related

Chat Application using SignalR and Ionic

I am developing a chat application.I use SignalR and Ionic for this.And I get an error on the Ionic side.
Startup.cs
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SignalR.Startup))]
namespace SignalR
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
ChatHub.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalR
{
public class ChatHub : Hub
{
public void Send(string username,string message)
{
Clients.All.sendMessage(username,message);
}
}
}
controller.js
angular.module('starter.controllers', [])
.controller('DashCtrl', function ($scope) {
$scope.name = 'Onur'; // holds the user's name
$scope.message = ''; // holds the new message
$scope.messages = []; // collection of messages coming from server
$scope.chatHub = null; // holds the reference to hub
$scope.chatHub = $.connection.chatHub; // initializes hub
$.connection.hub.start(); // starts hub
// register a client method on hub to be invoked by the server
$scope.chatHub.client.broadcastMessage = function (name, message) {
var newMessage = name + ' says: ' + message;
// push the newly coming message to the collection of messages
$scope.messages.push(newMessage);
$scope.$apply();
};
$scope.newMessage = function () {
// sends a new message to the server
$scope.chatHub.server.sendMessage($scope.name, $scope.message);
$scope.message = '';
};
})
Faield to load resource
hubs(0,0)
TypeError: Cannot read property 'chatHub' of undefined
I'm getting errors.Where am I doing wrong.Help me
You need to start the hub after registering client methods. It should work.

How to upload video with Facebook graph API

I've been struggling for weeks to get figure out how to upload video using the graph api. I've gone through all the documentation and i just don't understand what i must do to get a correct response from the graph api before i write the code. I've included an image.
Can someone just tell me like a child what I must put in exactly?
Figured out how to use graph api with c# for unity.
you can post a comment and post a video.
the url given is just an open video that was available, choose your own if you want, or if it becomes unavailable in the future.
enjoy!
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using Facebook.Unity;
using Facebook.MiniJSON;
public class FBVideoPost : MonoBehaviour {
// Use this for initialization
void Start () {
// this is to post string
postStatus ();
//this is to post video
this.StartCoroutine(this.StartVideoUpload());
}
void postStatus()
{
var formdata = new Dictionary<string, string>();
formdata.Add ("message", "This is my third post!");
FB.API("/me/feed", HttpMethod.POST, delegate (IGraphResult callback){
Debug.Log ("This is a test!");
},formdata);
}
private IEnumerator StartVideoUpload()
{
yield return new WaitForEndOfFrame();
WWW www = new WWW("http://techslides.com/demos/sample-videos/small.mp4");
while(!www.isDone) {
yield return null;
Debug.Log("progress : "+www.progress);
}
Debug.Log("size : "+www.size);
var wwwForm = new WWWForm();
wwwForm.AddBinaryData("file", www.bytes, "Video.MOV","multipart/form-data");
wwwForm.AddField("title", "Hello World");
wwwForm.AddField("description", "How you doing?");
FB.API("me/videos", HttpMethod.POST, UploadFinish, wwwForm);
}
private void UploadFinish(IGraphResult result) {
Debug.Log("result : "+result.ToString()+" , error : "+result.Error);
}
}
I will post another forum thread where you answered yourself and that helped me in addition to your answer here.
http://answers.unity3d.com/questions/1167534/how-to-send-file-local-path-using-wwwform-on-ios-a.html
In short, for anyone looking to "Upload Videos using the FB SDK from iOS", follow Luke's answer and add the following:
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using Facebook.Unity;
using Facebook.MiniJSON;
public class FBVideoPost : MonoBehaviour {
// Use this for initialization
void Start () {
// this is to post string
postStatus ();
//this is to post video
this.StartCoroutine(this.StartVideoUpload());
}
void postStatus()
{
var formdata = new Dictionary<string, string>();
formdata.Add ("message", "This is my third post!");
FB.API("/me/feed", HttpMethod.POST, delegate (IGraphResult callback){
Debug.Log ("This is a test!");
},formdata);
}
private IEnumerator StartVideoUpload()
{
yield return new WaitForEndOfFrame();
///ADD THIS
//this is the path to your file.
String VideoLocStr = Application.persistentDataPath + "Your_Video.mov"
String pathForIOS = VideoLocStr.Replace (" ","%20");
WWW www = new WWW(pathForIOS);
///
while(!www.isDone) {
yield return null;
Debug.Log("progress : "+www.progress);
}
Debug.Log("size : "+www.size);
var wwwForm = new WWWForm();
wwwForm.AddBinaryData("file", www.bytes, "Your_Video.mov","multipart/form-data");
wwwForm.AddField("title", "Hello World");
wwwForm.AddField("description", "How you doing?");
FB.API("me/videos", HttpMethod.POST, UploadFinish, wwwForm);
}
private void UploadFinish(IGraphResult result) {
Debug.Log("result : "+result.ToString()+" , error : "+result.Error);
}
}
Thanks, Luke.
Good luck to everyone.

Claims transformation in ADFS 3.0 by making a call to REST API

We have a ASP.NET Web API (REST service) in our enterprise that gives us the list of coarse-grained claims for a user that we want to inject into the adfs token before passing the token onto the application. Does anyone know if making a rest call is possible using the Custom attribute store (by passing param's to the custom attribute store from the Claims rule language in ADFS 3.0) ?
Any help regarding this would be greatly appreciated!
Thanks,
Ady.
I'm able to make the REST call from the Custom Attribute store. For those who are still wondering about this can look at the below code.
using System;
using System.Collections.Generic;
using System.Text;
using System.IdentityModel;
using Microsoft.IdentityServer.ClaimsPolicy.Engine.AttributeStore;
using System.Net.Http;
using System.Net;
namespace CustomAttributeStores
{
public class CoarseGrainClaimsAttributeStore : IAttributeStore
{
#region Private Members
private string API_Server = "https://<Server Name>/API/";
#endregion
#region IAttributeStore Members
public IAsyncResult BeginExecuteQuery(string query, string[] parameters, AsyncCallback callback, object state)
{
string result = string.Empty;
if (parameters == null)
{
throw new AttributeStoreQueryFormatException("No query parameter.");
}
if (parameters.Length != 1)
{
throw new AttributeStoreQueryFormatException("More than one query parameter.");
}
string userName = parameters[0];
if (userName == null)
{
throw new AttributeStoreQueryFormatException("Query parameter cannot be null.");
}
//Ignore SSL Cert Error
//TODO: Need to set the SSL cert correctly for PROD Deployment
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
using (var client = new HttpClient())
{
//The url can be passed as a query
string serviceUrl = API_Server + "GetAdditionalClaim";
serviceUrl += "?userName=" + userName;
//Get the SAML token from the API
result = client
.GetAsync(serviceUrl)
.Result
.Content.ReadAsStringAsync().Result;
result = result.Replace("\"", "");
}
string[][] outputValues = new string[1][];
outputValues[0] = new string[1];
outputValues[0][0] = result;
TypedAsyncResult<string[][]> asyncResult = new TypedAsyncResult<string[][]>(callback, state);
asyncResult.Complete(outputValues, true);
return asyncResult;
}
public string[][] EndExecuteQuery(IAsyncResult result)
{
return TypedAsyncResult<string[][]>.End(result);
}
public void Initialize(Dictionary<string, string> config)
{
// No initialization is required for this store.
}
#endregion
}
}
No, you can't do this with the claims rules language.
This is somewhat of a hack but you could write the claims to e.g. a DB and then use a custom attribute store
If you have access to WIF on the client side, you can augment the claims there e.g. Adding custom roles to windows roles in ASP.NET using claims.

Consuming wsdl using c# but getting error: "SOAP header To was not understood "

I am consuming wsdl using c# and I'm geting back the following error
"SOAP header To was not understood".
What is causing this problem and how do I solve it?
Thanks for your response ,
According to your suggestion, i tried this code :
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class MyHeader : SoapHeader
{
public bool _MustUnderstand;
public MyHeader() { }
public bool MustUnderstand
{
get { return _MustUnderstand; }
set { _MustUnderstand = value; }
}
}
public class Service : System.Web.Services.WebService
{
public MyHeader MustUnderstand;
public Service ()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[SoapHeader("MustUnderstand")]
public void Nokia()
{
MustUnderstand = new MyHeader();
MustUnderstand.MustUnderstand = true;
WebService connect = new WebService();
long publicKeyK ;
publicKeyK= connect.GetPublicKey(out publicKeyK);
}
}
( I put also false on the mustUnderstand property ... )
I'm still get the same error message .
"SOAP header To was not understood "
Any Idea ?
Poli.
Any time you get a "SOAP header X was not understood" it means that the MustUnderstand property for that element has been set to true and that the consuming application does not "understand" or recognize that element. The application that is sending the message is probably setting the MustUnderstand property because I think it is not set or false by default.
see http://msdn.microsoft.com/en-us/library/system.servicemodel.messageheaderattribute.aspx

ASP.Net MVC 2.0 : Absolute action URL using HttpRuntime only (no HttpContext)

I need to build a URL for self-ping action. I want to initialize that URL from Application_Start, which doesn't have HttpContext (on ISS 7.0 integrated mode).
I have code to build absolute Action URL using HttpContext, now I need the same but use HttpRuntime instead.
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
class Program
{
static void Main()
{
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteTable.Routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
var request = new HttpRequest("/", "http://foo.com", "");
var response = new HttpResponse(new StringWriter());
var httpContext = new HttpContext(request, response);
var httpContextBase = new HttpContextWrapper(httpContext);
var routeData = new RouteData();
var requestContext = new RequestContext(httpContextBase, routeData);
var urlHelper = new UrlHelper(requestContext, RouteTable.Routes);
var url = urlHelper.Action("Index", "Home", new { id = "123" }, "http");
Console.WriteLine(url);
}
}
The following worked for me. It may not be the most eloquent way to create action URL's without a request, but it works. Improvements are welcome.
// Create an MVC UrlHelper to create our URL.
// Feed it with a mock RequestContext
UrlHelper urlHelper = new UrlHelper(
new RequestContext(
new HttpContextWrapper(
new HttpContext(
new HttpRequest("", "http://a.com", ""), // this can be any domain name -- it's not used in creating the URL
new HttpResponse(new StringWriter()))),
new RouteData()));
// UrlHelper creates a relative URL -- make sure to root it at our domain
Uri myNewUri = new Uri(
new Uri("http://mydomain.com"),
urlHelper.Action("myAction", "myController"));