I am creating an application in xamarin forms which needs synchronous web service call. But only GetAsync is available in xamarin forms. can anyone please explain me how to call synchronous web service call in xamarin forms?
Try something like this
public Webservice() { }
public Home GetHome()
{
string strpost = "";
var client = new System.Net.Http.HttpClient();
client.BaseAddress = new Uri(" xyz ");
var response = client.PostAsync(new Uri(" xyz "), str).Result;
var result = JsonConvert.DeserializeObject<Home>(response.Content.ReadAsStringAsync().Result);
Home home = new Home();
if (!Equals(result, null))
{
home = result;
return home;
}
}
Refer: https://forums.xamarin.com/discussion/43397/how-to-call-synchronous-webservice
Related
I use token auth for my WebApi application.
I have the following ConfigureAuth method in Startup class:
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
and ApplicationOAuthProvider:
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
private readonly string _publicClientId;
public ApplicationOAuthProvider(string publicClientId)
{
if (publicClientId == null)
{
throw new ArgumentNullException("publicClientId");
}
_publicClientId = publicClientId;
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
var user = await userManager.FindAsync(context.UserName, context.Password);
//ApplicationUser user = new ApplicationUser() { UserName ="a" };
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
so, I should call /Token and pass credentials to get token. It works, but I want to create Unit Test for it. Is it possible?
The only way to do that is by make an integration test, which asserts the full pipeline testing - from request to response. Before the actual test on the server, you can call the token endpoint to get it, and then use it in the actual unit test by attaching it to the response. I have a sample, which uses MyTested.WebApi here:
Sample
You can do the same without the testing library, this is just how to do it.
I like the idea of pluggable configuration.
For Unit Test project, I want to use specific identity and get predictable data fro LDAP. So, i use the following line in my unit test method when setting http configuration:
config.Filters.Add(new WebApiSetIdentityFilter(config, identityName));
where the filter just "hacks" the identity, replacing the fields I need:
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
//This principal flows throughout the request.
context.Principal = new GenericPrincipal(new GenericIdentity(this.IdentityName, "LdapAuthentication"), new string[0]);
}
We use to create email delegates through Google Email Settings API, but after the deprecation of OAuth 1.0 we were no longer able to authenticate properly. After doing some research I think we should create a service account, delegate domain-wide access for that service account, then authenticate using it. However I can't seem to get it to work, all I receive from Google is 401 unauthorized. Does someone know what I am doing wrong? Here is most of the code, I'm using .Net/c# and I'm using Google Apps for business.
ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer("serviceAccountEmail")
{
Scopes = new[] { "https://apps-apis.google.com/a/feeds/emailsettings/2.0/ " },
User = "admin email string"
}.FromCertificate({X509 certificate from service account p12 file}));
credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Wait(-1);
GoogleMailSettingsService service = new GoogleMailSettingsService("domain name", "appname");
service.SetAuthenticationToken(credential.Token.AccessToken);
service.CreateDelegate("delegator", "delegate");
For those who may need this answer in the future, I was able to provide a solution through the following. For reference I am running a web app using MVC framework, but the solution could be tweaked for a console or GUI standalone app as well.
Basically, I was able to authenticate the GoogleMailSettingsService.Service.RequestFactory with a GOAuth2RequestFactory object.
For instance:
GoogleMailSettingsService service = new GoogleMailSettingsService("domain", "applicationName");
service.RequestFactory = new GOAuth2RequestFactory("service", "AppName", new OAuth2Parameters() { AccessToken = AuthorizationCodeWebApp.AuthResult.Credential.Token.AccessToken });
Now for the AuthorizationCodeWebApp.AuthResult I implemented the following:
public async Task<ActionResult> DelegationMenu(CancellationToken cancellationToken)
{
var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellationToken);
if (result.Credential == null)
return new RedirectResult(result.RedirectUri); //Will redirect to login page for Google Admin to authenticate.
Session["AuthResult"] = result;
return View();
}
public class AppFlowMetadata : FlowMetadata
{
private static readonly IAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "ClientId",
ClientSecret = "ClientSecret"
},
Scopes = new[] { "https://apps-apis.google.com/a/feeds/emailsettings/2.0/" },
DataStore = new FileDataStore("C:\\OAuth2.0Tokens")
});
public override string GetUserId(Controller controller)
{
var user = controller.Session["user"];
if (user == null)
{
user = Guid.NewGuid();
controller.Session["user"] = user;
}
return user.ToString();
}
public override IAuthorizationCodeFlow Flow
{
get { return flow; }
}
}
A service account isn't required for this action. The Email Settings API, within the Admin SDK, allows a Super Admin to set a delegation for an account within the domain without the need to impersonate the user via a service account.
Check out this section of the Developers site for more information on this API. You can also test this on the OAuth Playground and add delegates right from there.
I have installed web app server and now the server is 192.168.1.103 on IIS and i have a sample code from this site https://code.msdn.microsoft.com/office/Building-an-Office-Web-f98650d6/view/Discussions#content
in this sample the appwopiserver in web config is:
"wopihost.wingtip.com:8888/api/wopi/files/"
How can i create api/wopi/files/ directory in my server ? in other words i want to change this code to connect to my server .
here is the code that get the link:
public Link GetLink([FromUri] FileRequest fileRequest)
{
if (ModelState.IsValid)
{
var xml = WebConfigurationManager.AppSettings["appDiscoveryXml"];
var wopiServer = WebConfigurationManager.AppSettings["appWopiServer"];
bool updateEnabled = false;
bool.TryParse(WebConfigurationManager.AppSettings["updateEnabled"], out updateEnabled);
WopiAppHelper wopiHelper = new WopiAppHelper(HostingEnvironment.MapPath(xml), updateEnabled);
var result = wopiHelper.GetDocumentLink(wopiServer + fileRequest.name);
var rv = new Link
{
Url = result
};
return rv;
}
throw new ApplicationException("Invalid ModelState");
}
the final created link to open office in browser in this sample is:
http://owa1.wingtip.com/we/wordeditorframe.aspx?WOPISrc=http%3a%2f%2fwopihost.wingtip.com%3a8888%2fapi%2fwopi%2ffiles%2ftest.docx&access_token=YMDZjBxXlD4%3dlxnjDAq1aib0yGsNDo%2fd0Jm4b5R8eJircFrcaU84fgQ%3d
but i want something like this:
(http:// 192.168.1.103/we/wordeditorframe.aspx?WOPISrc=http%3a%2f%2fwopihost.wingtip.com%3a8888%2fapi%2fwopi%2ffiles%2ftest.docx&access_token=YMDZjBxXlD4%3dlxnjDAq1aib0yGsNDo%2fd0Jm4b5R8eJircFrcaU84fgQ%3d)
You have to replace App_Data\Discovery.xml with an XML you find at http://192.168.1.103/hosting/discovery (your OWA server).
We have MVVM Silverlight application. I am trying to open web url from button click event which happen on client side viewmodel and through invoke method needs to open web url in new browser.
I am using Process.Start method as describe below in Server side code.
var URL = #"http://SiteSelect.aspx";
SecureString secure = new SecureString();
char[] passwordChars = Properties.Settings.Default.Password.ToCharArray();
//converting string to securestring...found from internet
foreach (char c in passwordChars)
{
secure.AppendChar(c);
}
Process.Start(URL,"",Properties.Settings.Default.User,secure,"agent");
this throws an error related to user name and password. I checked user name and password is correct. Anyone have solution or any other method I can able to use?
Thanks,
You create a helper class:
public static class CommonHelper
{
private class HyperlinkButtonWrapper : HyperlinkButton
{
public void OpenURL(string navigateUri)
{
OpenURL(new Uri(navigateUri, UriKind.Absolute));
}
public void OpenURL(Uri navigateUri)
{
base.NavigateUri = navigateUri;
base.TargetName = "_blank";
base.OnClick();
}
}
public static void OpenURL(string navigateUri)
{
new HyperlinkButtonWrapper().OpenURL(navigateUri);
}
}
Usage:
CommonHelper.OpenURL(#"http://SiteSelect.aspx");
You could use this as well :
using System.Windows.Browser;
var uri = new Uri("http://foo.fr");
HtmlPage.Window.Navigate(uri, "_blank");
Easiest way to pass credentials is to put them in the URL, however it's not very secured. Ie:
http://user:password#foo.fr
I'm looking for a way to authenticate a user (given a username and password) via the Microsoft CRM 4.0 Web Services API. Ideally, I'd like to filter down a list of projects based on which ones the logged in user has access to. i may be able to figure out the second part but I can't find a way to authenticate the user. The way all of the cals are currently made in the web service is via:
MyWebServices.CrmService svc = new MyWebServices.CrmService();
MyWebServices.CrmAuthenticationToken token = new MyWebServices.CrmAuthenticationToken();
token.OrganizationName = "MyCRM";
token.AuthenticationType = 0;
svc.CrmAuthenticationTokenValue = token;
svc.PreAuthenticate = true;
svc.Credentials = System.Net.CredentialCache.DefaultCredentials;
svc.Credentials = new NetworkCredential("hj", "mypass", "mydomain");
Then calls can be made via the service. I guess I could potentially try to authenticate to CRM via the user's username/password but it feels wrong somehow.
If you are in an on-premise environment, you should be able to use the following code to get a valid CRM service that can be used to retrieve your projects.
public static Microsoft.Crm.SdkTypeProxy.CrmService GetCrmService(string crmServerUrl, string organizationName, System.Net.NetworkCredential networkCredential)
{
// Setup the Authentication Token
CrmAuthenticationToken crmAuthenticationToken = new CrmAuthenticationToken
{
OrganizationName = organizationName,
AuthenticationType = 0
};
var crmServiceUriBuilder = new UriBuilder(crmServerUrl) { Path = "//MSCRMServices//2007//CrmService.asmx" };
// Instantiate a CrmService
var crmService = new Microsoft.Crm.SdkTypeProxy.CrmService
{
Url = crmServiceUriBuilder.ToString(),
UseDefaultCredentials = false,
Credentials = networkCredential,
CrmAuthenticationTokenValue = crmAuthenticationToken
};
return crmService;
}