How to programmatically create a BasicHttpBinding? - c#

I have to following code:
BasicHttpBinding binding = new BasicHttpBinding ();
Uri baseAddress = new Uri ("URL.svc");
EndpointAddress endpointAddress = new EndpointAddress (baseAddress);
var myChannelFactory = new ChannelFactory<IMyInterface> (binding, endpointAddress);
IMyInterface client = null;
try
{
client = myChannelFactory.CreateChannel ();
var a = client.WsFunction ("XXXXXX");
((ICommunicationObject)client).Close ();
}
catch
{
if (client != null)
{
((ICommunicationObject)client).Abort ();
}
}
Where "IMyInterface" is the interface that my WS implements.. for example:
[ServiceContract]
public interface IMyInterface
{
[OperationContract]
Result WsFunction1 (string param);
[OperationContract]
Result WsFunction2 (string param);
[OperationContract]
Result WsFunction3 (string param);
}
And it returns something like this:
[DataContract]
public class Result
{
string a = "";
string b = "";
[DataMember]
public string A
{
get { return a; }
set { a = value; }
}
[DataMember]
public string B
{
get { return b; }
set { b = value; }
}
}
When I run this code, I can reach the WS, but I can never get the Result filled out.
What am I doing wrong?
Thanks in advance!

The easiest way to access a service via a BasicHttpBinding is to generate the client code from SlSvcUtil.exe, which is a silverlight utility application.
SLsvcUtil.exe /directory:C:\users\me\Desktop http://URL.svc
That should create a MyInterfaceClient class inside of the file it generates.
Then in your code you can do:
var binding = new BasicHttpBinding() {
Name = "BindingName",
MaxBufferSize = 2147483647,
MaxReceivedMessageSize = 2147483647
};
var endpoint = new EndpointAddress("URL.svc");
MyInterfaceClient client = new MyInterfaceClient(binding, endpoint);
client.WSFunctionCompleted += (object sender, WSFunctionCompletedEventArgs e) => {
//access e.Result here
};
client.WSFunctionAsync("XXXXXX");
Your mileage may vary. Let me know if this works.

var binding = new BasicHttpBinding();
binding.ProxyAddress = new Uri(string.Format("http://{0}:{1}", proxyAddress, proxyPort));
binding.UseDefaultWebProxy = false;
binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Basic;
var endpoint = new EndpointAddress("serviceadress");
var authenticationClient = new WOKMWSAuthenticateClient(binding, endpoint);
authenticationClient.ClientCredentials.UserName.UserName = username;
authenticationClient.ClientCredentials.UserName.Password = password;
if you want to run it on your local you should this code.
ServicePointManager.Expect100Continue = false;

Very easy and simple way to call WCF :
BasicHttpBinding myBinding = new BasicHttpBinding();
EndpointAddress myEndpoint = new EndpointAddress("http://localhost:3283/Service1.svc");
myBinding.ReaderQuotas.MaxArrayLength = int.MaxValue;
myBinding.MaxBufferSize = int.MaxValue;
myBinding.MaxReceivedMessageSize = int.MaxValue;
ChannelFactory<ITestAPI> myChannelFactory = new ChannelFactory<ITestAPI>(myBinding, myEndpoint);
ITestAPI instance = myChannelFactory.CreateChannel();
Test data = new Test();
data.helloName = name;
data= instance.GetMyName(data);
myChannelFactory.Close();

Related

How to fix Amazon.Rekognition.AmazonRekognitionException?

I am getting AmazonRekognitionException as below when trying to run CompareFacesResponse, I am stuck, what should I do or check?
Amazon.Rekognition.AmazonRekognitionException: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details. ---> Amazon.Runtime.Internal.HttpErrorResponseException: Exception of type 'Amazon.Runtime.Internal.HttpErrorResponseException' was thrown
AWS credentials access key and secret are checked and correct
public static async Task<Tuple<bool, string>> Rekognition_Compare_Faces(string _source, string _target, string _bucketName)
{
const string HOSTNAME = "https://rekognition.ap-southeast-1.amazonaws.com/";
const string ACCESS_KEY = "my_access_key";
const string ACCESS_SECRET = "my_secret_key";
float _similarityThreshold = 70F;
bool _ret = false;
string _confidence = string.Empty;
try
{
AmazonRekognitionConfig _config = new AmazonRekognitionConfig();
_config.ServiceURL = HOSTNAME + _bucketName;
AmazonRekognitionClient _rekognitionClient = new AmazonRekognitionClient(ACCESS_KEY, ACCESS_SECRET, _config);
Amazon.Rekognition.Model.Image _imageSource = new Amazon.Rekognition.Model.Image();
Amazon.Rekognition.Model.Image _imageTarget = new Amazon.Rekognition.Model.Image();
Amazon.Rekognition.Model.S3Object _s3_source = new Amazon.Rekognition.Model.S3Object { Bucket = _bucketName, Name = _source };
Amazon.Rekognition.Model.S3Object _s3_target = new Amazon.Rekognition.Model.S3Object { Bucket = _bucketName, Name = _target };
CompareFacesRequest _compareFacesRequest = new CompareFacesRequest()
{
SourceImage = new Amazon.Rekognition.Model.Image
{
S3Object = new Amazon.Rekognition.Model.S3Object
{
Bucket = HOSTNAME + _bucketName,
Name = _source
}
},
TargetImage = new Amazon.Rekognition.Model.Image
{
S3Object = new Amazon.Rekognition.Model.S3Object
{
Bucket = HOSTNAME + _bucketName,
Name = _target
}
},
SimilarityThreshold = _similarityThreshold
};
// IT THROWN HERE!!
CompareFacesResponse _compareFacesResponse = await _rekognitionClient.CompareFacesAsync(_compareFacesRequest);
// Display results
foreach (CompareFacesMatch match in _compareFacesResponse.FaceMatches)
{
ComparedFace face = match.Face;
BoundingBox position = face.BoundingBox;
_confidence = match.Similarity.ToString(AppSettings.Decimal_Number_Format) + "%";
_ret = true;
}
}
catch (Exception ex) { await ClsMain.SaveLog("AWS.Compare_Faces: " + ex.ToString()); }
finally { }
return await Task.FromResult(new Tuple<bool, string>(_ret, _confidence));
}
has anybody experience on this?
thanks a lot in advance
Regards
Don
I had the same error.
I tried adding RegionEndpoint = RegionEndpoint.EUWest1 to my AmazonRekognitionConfig so it now looks like this:
var config = new AmazonRekognitionConfig
{
ServiceURL = $"https://rekognition.ap-southeast-1.amazonaws.com/{_awsSettings.BucketName}",
RegionEndpoint = RegionEndpoint.EUWest1
};
var client = new AmazonRekognitionClient(_awsSettings.AccessKey, _awsSettings.Secret, config);
This fixed the problem for me.

CefSharp 3 set proxy at Runtime

I downloaded CEF (chromuim embedded framework) binary distributation that comes with (cefclient & cefsimple) c++ examples, And Realized that cefclient can change proxy settings on run-time.
And the key to do that is to Grab the RequestContext and call the function SetPreference.
on CefClient all works just nice.
but on CefSharp calling SetPreference always returns false, and also HasPreference returns false for the preference name "proxy".
thanks to amaitland the proper way to actively inforce changing the request-context prefrences, is to run the code on CEF UIThread as following:
Cef.UIThreadTaskFactory.StartNew(delegate {
var rc = this.browser.GetBrowser().GetHost().RequestContext;
var v = new Dictionary<string, object>();
v["mode"] = "fixed_servers";
v["server"] = "scheme://host:port";
string error;
bool success = rc.SetPreference("proxy", v, out error);
//success=true,error=""
});
if anyone need any other soulition i found this solution.
Cef.UIThreadTaskFactory.StartNew(delegate
{
string ip = "ip or adress";
string port = "port";
var rc = this.browser.GetBrowser().GetHost().RequestContext;
var dict = new Dictionary<string, object>();
dict.Add("mode", "fixed_servers");
dict.Add("server", "" + ip + ":" + port + "");
string error;
bool success = rc.SetPreference("proxy", dict, out error);
});
I downloaded CefSharp.WinForms 65.0.0 and made class, that can help to start working with proxy:
public class ChromeTest
{
public static ChromiumWebBrowser Create(WebProxy proxy = null, Action<ChromiumWebBrowser> onInited = null)
{
var result = default(ChromiumWebBrowser);
var settings = new CefSettings();
result = new ChromiumWebBrowser("about:blank");
if (proxy != null)
result.RequestHandler = new _requestHandler(proxy?.Credentials as NetworkCredential);
result.IsBrowserInitializedChanged += (s, e) =>
{
if (!e.IsBrowserInitialized)
return;
var br = (ChromiumWebBrowser)s;
if (proxy != null)
{
var v = new Dictionary<string, object>
{
["mode"] = "fixed_servers",
["server"] = $"{proxy.Address.Scheme}://{proxy.Address.Host}:{proxy.Address.Port}"
};
if (!br.GetBrowser().GetHost().RequestContext.SetPreference("proxy", v, out string error))
MessageBox.Show(error);
}
onInited?.Invoke(br);
};
return result;
}
private class _requestHandler : DefaultRequestHandler
{
private NetworkCredential _credential;
public _requestHandler(NetworkCredential credential = null) : base()
{
_credential = credential;
}
public override bool GetAuthCredentials(IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
{
if (isProxy == true)
{
if (_credential == null)
throw new NullReferenceException("credential is null");
callback.Continue(_credential.UserName, _credential.Password);
return true;
}
return false;
}
}
}
Using:
var p = new WebProxy("Scheme://Host:Port", true, new[] { "" }, new NetworkCredential("login", "pass"));
var p1 = new WebProxy("Scheme://Host:Port", true, new[] { "" }, new NetworkCredential("login", "pass"));
var p2 = new WebProxy("Scheme://Host:Port", true, new[] { "" }, new NetworkCredential("login", "pass"));
wb1 = ChromeTest.Create(p1, b => b.Load("http://speed-tester.info/check_ip.php"));
groupBox1.Controls.Add(wb1);
wb1.Dock = DockStyle.Fill;
wb2 = ChromeTest.Create(p2, b => b.Load("http://speed-tester.info/check_ip.php"));
groupBox2.Controls.Add(wb2);
wb2.Dock = DockStyle.Fill;
wb3 = ChromeTest.Create(p, b => b.Load("http://speed-tester.info/check_ip.php"));
groupBox3.Controls.Add(wb3);
wb3.Dock = DockStyle.Fill;
If you want dynamic proxy resolver (proxy hanlder), which allow you to use different proxy for different host - you should:
1) Prepare javascript
var proxy1Str = "PROXY 1.2.3.4:5678";
var proxy2Str = "PROXY 2.3.4.5:6789";
var ProxyPacScript =
$"var proxy1 = \"{(proxy1Str.IsNullOrEmpty() ? "DIRECT" : proxy1Str)}\";" +
$"var proxy2 = \"{(proxy2Str.IsNullOrEmpty() ? "DIRECT" : proxy2Str)}\";" +
#"function FindProxyForURL(url, host) {
if (shExpMatch(host, ""*example.com"")) {
return proxy1;
}
return proxy2;
}";
var bytes = Encoding.UTF8.GetBytes(ProxyPacScript);
var base64 = Convert.ToBase64String(bytes);
2) Set it correctly
var v = new Dictionary<string, object>();
v["mode"] = "pac_script";
v["pac_url"] = "data:application/x-ns-proxy-autoconfig;base64," + base64;
3) Call SetPreference as in accepted answer https://stackoverflow.com/a/36106994/9252162
As result all request to *example.com will flow throught proxy1, all others through proxy2.
To do it I spent all day but with help of source (https://cs.chromium.org/) I found solution. Hope it helps someone.
Main problems:
1) In new version (72 or 74 as I remember) there is no ability to use "file://..." as pac_url.
2) We can't use https://developer.chrome.com/extensions/proxy in cef.. or i can't find how to do it.
p.s. How to use another types of proxy (https, socks) - https://chromium.googlesource.com/chromium/src/+/master/net/docs/proxy.md#evaluating-proxy-lists-proxy-fallback
With the new version of CefSharp, it's quite simple to set proxy:
browser = new ChromiumWebBrowser();
panel1.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
await browser.LoadUrlAsync("about:blank");
await Cef.UIThreadTaskFactory.StartNew(() =>
{
browser.GetBrowser().GetHost().RequestContext.SetProxy("127.0.0.1", 1088, out string _);
});

Calling a WCF service with certificate from a client application without having the contract interface

My particular problem is something like this:
I am able to invoke WCF service dynamically, but i need to provide certificate.
We don't want to use app.config.
Major issue is that WCF service is a 3rd party url.
Actually, i am getting an exception while invoke instance that certificate is not provided.
My code is something like this:
try
{
// Define the metadata address, contract name, operation name,
// and parameters.
// You can choose between MEX endpoint and HTTP GET by
// changing the address and enum value.
Uri mexAddress = new Uri("http://Some3rdPartyURL.svc?wsdl");//Some 3rd party url
// For MEX endpoints use a MEX address and a
// mexMode of .MetadataExchange
MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet;
string contractName = "IService";//"";//3rd party service name
string operationName = "SendMethod";//3rd party method name
object[] args = new object[] { "", "", "0" };//3rd party required parameters
//object[] operationParameters = new object[] { /*1, 2*/args };
// Get the metadata file from the service.
MetadataExchangeClient mexClient =
new MetadataExchangeClient(mexAddress, mexMode);
mexClient.ResolveMetadataReferences = true;
MetadataSet metaSet = mexClient.GetMetadata();
// Import all contracts and endpoints
WsdlImporter importer = new WsdlImporter(metaSet);
Collection<ContractDescription> contracts =
importer.ImportAllContracts();
ServiceEndpointCollection allEndpoints = importer.ImportAllEndpoints();
// Generate type information for each contract
ServiceContractGenerator generator = new ServiceContractGenerator();
var endpointsForContracts = new Dictionary<string, IEnumerable<ServiceEndpoint>>();
foreach (ContractDescription contract in contracts)
{
generator.GenerateServiceContractType(contract);
// Keep a list of each contract's endpoints
endpointsForContracts[contract.Name] = allEndpoints.Where(
se => se.Contract.Name == contract.Name).ToList();
}
if (generator.Errors.Count != 0)
throw new Exception("There were errors during code compilation.");
// Generate a code file for the contracts
CodeGeneratorOptions options = new CodeGeneratorOptions();
options.BracingStyle = "C";
CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("C#");
// Compile the code file to an in-memory assembly
// Don't forget to add all WCF-related assemblies as references
CompilerParameters compilerParameters = new CompilerParameters(
new string[] {
"System.dll", "System.ServiceModel.dll",
"System.Runtime.Serialization.dll"});
compilerParameters.GenerateInMemory = true;
CompilerResults results = codeDomProvider.CompileAssemblyFromDom(
compilerParameters, generator.TargetCompileUnit);
if (results.Errors.Count > 0)
{
throw new Exception("There were errors during generated code compilation");
}
else
{
// Find the proxy type that was generated for the specified contract
// (identified by a class that implements
// the contract and ICommunicationbject)
Type clientProxyType = results.CompiledAssembly.GetTypes().First(
t => t.IsClass &&
t.GetInterface(contractName) != null &&
t.GetInterface(typeof(ICommunicationObject).Name) != null);
// Get the first service endpoint for the contract
ServiceEndpoint se = endpointsForContracts[contractName].First();
//se = endpointsForContracts[contractName].First();
WSHttpBinding wsBinding = this.fillWsHttpBinding();
string encodeValue = "MIIFazCCBFO****"; // here we should use the encoded certificate value generated by svcutil.exe.
X509Certificate2Collection supportingCertificates = new X509Certificate2Collection();
supportingCertificates.Import(Convert.FromBase64String(encodeValue));
X509Certificate2 primaryCertificate = supportingCertificates[0];
supportingCertificates.RemoveAt(0);
EndpointIdentity.CreateX509CertificateIdentity(primaryCertificate, supportingCertificates);
EndpointIdentity identity = EndpointIdentity.CreateX509CertificateIdentity(primaryCertificate);
var endpoint = new EndpointAddress(mexAddress, identity);
se.Binding = wsBinding;
se.Address = endpoint;
// Create an instance of the proxy
// Pass the endpoint's binding and address as parameters
// to the ctor
object instance = results.CompiledAssembly.CreateInstance(
clientProxyType.Name,
false,
System.Reflection.BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance,
null,
new object[] { se.Binding, se.Address }, CultureInfo.CurrentCulture, null);
var methodInfo = instance.GetType().GetMethod(operationName);
var methodParams = methodInfo.GetParameters();
int count = args.Count();
object[] args2 = new object[count];
int i = 0;
foreach (var service1 in methodParams)
{
args2[i] = Convert.ChangeType(args[i], Type.GetType("System." + service1.ParameterType.Name));
i += 1;
}
Object retVal = instance.GetType().GetMethod(operationName).Invoke(instance, args2);/*Getting Error that certificate not provided???*/
}
}
catch (Exception ex)
{
string error = ex.ToString();
MessageBox.Show("Error Invoking Method: " + ex.Message);
}
private WSHttpBinding fillWsHttpBinding()
{
WSHttpBinding wsBinding = new WSHttpBinding();
wsBinding.CloseTimeout = new TimeSpan(0, 1, 0);
wsBinding.OpenTimeout = new TimeSpan(0, 10, 0);
wsBinding.ReceiveTimeout = new TimeSpan(0, 10, 0);
wsBinding.SendTimeout = new TimeSpan(0, 5, 30);
wsBinding.BypassProxyOnLocal = false;
wsBinding.TransactionFlow = false;
wsBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
wsBinding.MaxBufferPoolSize = 524288L;
wsBinding.MaxReceivedMessageSize = 10485760L;
wsBinding.MessageEncoding = WSMessageEncoding.Text;
wsBinding.TextEncoding = Encoding.UTF8;
wsBinding.UseDefaultWebProxy = true;
wsBinding.AllowCookies = false;
wsBinding.ReaderQuotas.MaxDepth = 32;
wsBinding.ReaderQuotas.MaxStringContentLength = 8192;
wsBinding.ReaderQuotas.MaxArrayLength = 10485760;
wsBinding.ReaderQuotas.MaxNameTableCharCount = 16384;
wsBinding.ReliableSession.Ordered = true;
wsBinding.ReliableSession.InactivityTimeout = TimeSpan.FromMinutes(10);
wsBinding.ReliableSession.Enabled = false;
wsBinding.Security.Mode = SecurityMode.Message;
wsBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
wsBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
wsBinding.Security.Transport.Realm = "";
wsBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
wsBinding.Security.Message.NegotiateServiceCredential = true;
wsBinding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic256;
return wsBinding;
}
Where you are setting the certificate on the EndpointIdentity causes it to be used to validate the service's identity. You haven't set the client's credentials using instance.ClientCredentials.ClientCertificate.SetCertificate(...). You'll have to get the ClientCredentials from the ClientBase<> using reflection. See http://msdn.microsoft.com/en-us/library/ms732391%28v=vs.110%29.aspx.
var credentialProperty = instance.GetType().GetProperty("ClientCredentials");
var credentials = (ClientCredentials)credentialProperty.GetValue(instance, null);
credentials.ClientCertificate.SetCertficate(...);
You've also got two calls to EndpointIdentity.CreateX509CertificateIdentity, ignoring the output of one of them.

Callling a wcf within android app and passing listview selected item

I know I posted a question the other day about how should I be passing a selected android listview item to the a wcf serivce application. I am just trying to use the simplest approach to get things working. I am having the problem of getting the towns from the selected county using a wcf. I have a county table with id and county. In a towns table I have id, name and countyid.
Here is my wcf service application:
[OperationContract]
Festivalwrapper GetTownDataByCounty(int? id);
public Festivalwrapper GetTownDataByCounty(int? id)
{
Festivalwrapper returnType = new Festivalwrapper();
using (azureDBDataContext c = new azureDBDataContext())
{
returnType.TownList = (from town in c.Towns
where town.CountyID.Equals(id)
select new TownVM()
{
ID = town.ID,
Name = town.Name,
}).ToList();
}
return returnType;
}
Here is my OnItemClick for my first activity:
public void OnItemClick(AdapterView parent, View view, int position, long id)
{
var selectedValue = parent.GetItemIdAtPosition(position);
//InitializeDataTownById(int position);
var Intent = new Intent(this, typeof(SelectLocationActivity));
// selectedValue should already be a string but...
Intent.PutExtra("Name", selectedValue.ToString());
StartActivity(Intent);
}
And my second activity:
[Activity(Theme = "#style/Theme.AppCompat.Light")]
public class SelectLocationActivity : Activity
{
private DataTransferProcClient _client;
TextView _getTownsTextView;
ListView _listView;
public static readonly EndpointAddress EndPoint = new EndpointAddress("http://10.0.2.2:3190/DataTransferProc.svc");
//private int id;
protected override void OnCreate(Bundle bundle)
{
//var id = Intent.GetStringExtra("position");
base.OnCreate(bundle);
SetContentView(Resource.Layout.selectLocation);
_listView = FindViewById<ListView>(Resource.Id.lvTowns);
//_listView.OnItemClickListener = this;
_listView.FastScrollEnabled = true;
_getTownsTextView = FindViewById<TextView>(Resource.Id.getTownsTextView);
InitializeDataTownById();
}
#region InitializeDataTown
private void InitializeDataTownById()
{
var id = Intent.GetStringExtra("Name");
int value;
int.TryParse(id, out value);
if (id != null)
{
BasicHttpBinding binding = CreateBasicHttp();
_client = new DataTransferProcClient(binding, EndPoint);
_client.GetTownDataByCountyCompleted += ClientOnDataTransferProcCompleted;
_client.GetTownDataByCountyAsync(id);
}
//_client.Close ();
}
#endregion
#region CreateBasicHttp
private static BasicHttpBinding CreateBasicHttp()
{
var binding = new BasicHttpBinding()
{
Name = "basicHttpBinding",
MaxReceivedMessageSize = 67108864,
};
binding.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas()
{
MaxArrayLength = 2147483646,
MaxStringContentLength = 5242880,
};
var timeout = new TimeSpan(0, 1, 0);
binding.SendTimeout = timeout;
binding.OpenTimeout = timeout;
binding.ReceiveTimeout = timeout;
return binding;
}
#endregion
#region ClientOnDataTransferProcCompleted
//test connection to wcf, if doesn't work, you'll get an error
private void ClientOnDataTransferProcCompleted(object sender, GetTownDataByCountyCompletedEventArgs getTownDataByCountyCompletedEventArgs)
{
string msg = null;
if (getTownDataByCountyCompletedEventArgs.Error != null)
{
msg = getTownDataByCountyCompletedEventArgs.Error.Message;
msg += getTownDataByCountyCompletedEventArgs.Error.InnerException;
RunOnUiThread(() => _getTownsTextView.Text = msg);
}
else if (getTownDataByCountyCompletedEventArgs.Cancelled)
{
msg = "Request was cancelled.";
RunOnUiThread(() => _getTownsTextView.Text = msg);
}
else
{
msg = getTownDataByCountyCompletedEventArgs.Result.ToString();
TestAndroid.Festivalwrapper testHolder = getTownDataByCountyCompletedEventArgs.Result;
List<string> holder = testHolder.TownList.Select(item => item.Name).ToList();
/*foreach (TestAndroid.CountyVM item in TestHolder.CountyList)
{
holder.Add (item.Name);
}*/
RunOnUiThread(() => _listView.Adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, holder));
}
}
#endregion
I am also having a problem converting the string into an int. I am getting errors at : _client.GetTownDataByCountyAsync(id);
Error CS1503: Argument 1: cannot convert from 'string' to 'int' (CS1503)
Error CS1502: The best overloaded method match for 'DataTransferProcClient.GetTownDataByCountyAsync(int)' has some invalid arguments (CS1502)
string num;
int num2;
num = "2";
// method 1 - will throw Exception if num is not a parsable int
num2 = int.Parse(num);
// method 2 - will not throw exception - if success is true num2 will contain the parsed int
bool success = int.TryParse(num,out num2);

WebConsumer.ProcessUserAuthorization returns null

I use DotNetOpenAuth.
So.. I am getting looking good response which has state Authenticated.
That is fine.
Now I want to get user profile info but always getting NULL.
Here is the code.
private ServiceProviderDescription GetServiceDescription()
{
string ValidateTokenEndPoint = ConfigurationManager.AppSettings["identityOAuthValidateTokenEndPointUrl"];
string ValidateAuthorizationHeaderEndPoint = ConfigurationManager.AppSettings["identityOAuthValidateAuthorizationHeaderEndPointUrl"];
string AccessTokenEndPoint = ConfigurationManager.AppSettings["identityOAuthAccessTokenURL"];
bool UseVersion10A = Convert.ToBoolean(ConfigurationManager.AppSettings["identityOAuthUseVersion10a"]);
string RequestTokenStr = ConfigurationManager.AppSettings["identityOAuthRequestTokenURL"];
string UserAuthStr = ConfigurationManager.AppSettings["identityOAuthAuthorizeUserURL"];
string AccessTokenStr = ConfigurationManager.AppSettings["identityOAuthAccessTokenURL"];
string InvalidateTokenStr = ConfigurationManager.AppSettings["identityOAuthRequestInvalidateTokenURL"];
return new ServiceProviderDescription
{
AccessTokenEndpoint = new MessageReceivingEndpoint(AccessTokenStr, HttpDeliveryMethods.PostRequest),
RequestTokenEndpoint = new MessageReceivingEndpoint(RequestTokenStr, HttpDeliveryMethods.PostRequest),
UserAuthorizationEndpoint = new MessageReceivingEndpoint(UserAuthStr, HttpDeliveryMethods.PostRequest),
TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
ProtocolVersion = DotNetOpenAuth.OAuth.ProtocolVersion.V10a
};
}
void GetUserProfile()
{
var tokenManager = TokenManagerFactory.GetTokenManager(TokenManagerType.InMemoryTokenManager);
tokenManager.ConsumerKey = ConfigurationManager.AppSettings["identityOAuthConsumerKey"];
tokenManager.ConsumerSecret = ConfigurationManager.AppSettings["identityOAuthConsumerSecret"];
var serviceDescription = GetServiceDescription();
var consumer = new WebConsumer(serviceDescription, tokenManager);
var result = consumer.ProcessUserAuthorization(response);
if (result != null) // It is always null
{
}
Well I checked 10 times and I am pretty sure that all URLs to create ServiceProviderDescription are correct.
Any clue?
Well
finally check your web.config app keys
add key="identityOAuthConsumerKey" value="put here correct data!!!"
add key="identityOAuthConsumerSecret" value="put here correct data!!!"
and if you use hosts file you have to put correct sitename as well
127.0.0.1 site1.host1.com

Categories