I am using a library called SwaggerWcf to generate Swagger definitions for my application hosting a WCF REST API. I have finally made it work as I want it with the following code:
var swaggerHost = new WebServiceHost(typeof(SwaggerWcfEndpoint));
var endpoint =
new WebHttpEndpoint(
ContractDescription.GetContract(typeof(ISwaggerWcfEndpoint)),
new EndpointAddress("http://localhost/docs"))
{
AutomaticFormatSelectionEnabled = true,
FaultExceptionEnabled = true
};
// required to generate the swagger content
var e = new SwaggerWcfEndpoint();
swaggerHost.AddServiceEndpoint(endpoint);
var apiHost = new WebServiceHost(typeof(RestDataInterface));
var endpoint2 =
new WebHttpEndpoint(
ContractDescription.GetContract(typeof(IRestDataInterface)),
new EndpointAddress("http://localhost/api"))
{
AutomaticFormatSelectionEnabled = true,
FaultExceptionEnabled = true
};
apiHost.AddServiceEndpoint(endpoint2);
swaggerHost.Open();
apiHost.Open();
My question now is: is this the right way of doing it? As you can see I am creating two WebServiceHost instances. One for swagger and one for my actual API. While this seems to work fine, am I missing something? This API is intended to be fast but does not need to handle many concurrent users.
Thank you
Related
How do i fix this. I want to set my authentication in my code and not on the machine.
I have checked almost every answer on stackoverflow and github, but none has a good explanation.
How do i pass the credentials to the create intent, it throws this error.
InvalidOperationException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
GoogleCredential credential =
GoogleCredential.FromFile(file);
//var credential = GoogleCredential.FromStream(
// Assembly.GetExecutingAssembly().GetManifestResourceStream("chatbot-a90a9-8f2fb910202d.json"))
// .CreateScoped(IntentsClient.DefaultScopes);
var storage = StorageClient.Create(credential);
var client = IntentsClient.Create();
var text = new Intent.Types.Message.Types.Text();
text.Text_.Add("Message Text");
var message = new Intent.Types.Message()
{
Text = text
};
var trainingPhrasesParts = new List<string>
{
"Book a fligt",
"check cheap flights"
};
var phraseParts = new List<Intent.Types.TrainingPhrase.Types.Part>();
foreach (var part in trainingPhrasesParts)
{
phraseParts.Add(new Intent.Types.TrainingPhrase.Types.Part()
{
Text = part
});
}
var trainingPhrase = new Intent.Types.TrainingPhrase();
trainingPhrase.Parts.AddRange(phraseParts);
var intent = new Intent();
intent.DisplayName = "test";
intent.Messages.Add(message);
intent.TrainingPhrases.Add(trainingPhrase);
var newIntent = client.CreateIntent(
parent: new AgentName("chatbot-a90a9"),
intent: intent
);
SOLVED.
I change
var client = IntentsClient.Create();
To
IntentsClientBuilder builder = new IntentsClientBuilder
{
CredentialsPath = file, // Relative to where the code is executing or absolute path.
// Scopes = IntentsClient.DefaultScopes // Commented out because there's no need to specify this since you are using the defaults and all default values will be automatically used for values not specified in the builder.
};
IntentsClient client = builder.Build();
I am using Google.Apis.Pagespeedonline.v5 (nuget) to perform the analysis on my site.
By performing the analysis directly from the API Explorer site you can perform the test on all five categories.
https://developers.google.com/speed/docs/insights/v5/reference/pagespeedapi/runpagespeed
However, using the dotnet api, the category parameter only accepts one CategoryEnum, so, I can only get the result in one category per request.
I wonder if it is possible to get all categories in a single request
var initializer = new Initializer()
{
ApiKey = "XXXXXXXXXXXXXXX",
BaseUri = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed",
GZipEnabled = true
};
var service = new PagespeedonlineService(initializer);
var request = new RunpagespeedRequest(service, "https://www.google.com");
request.Category = CategoryEnum.Accessibility;
request.Locale = "pt";
request.Strategy = StrategyEnum.Desktop;
var response = request.Execute();
Well, you can do it this way:
GET https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed?category=ACCESSIBILITY&category=PERFORMANCE&locale=pt&strategy=DESKTOP&url=https%3A%2F%2Fwww.google.com%2F&prettyPrint=true&key=[YOUR_API_KEY] HTTP/1.1
But in your situation maybe you can change base URL to look like:
BaseUri = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?category=ACCESSIBILITY&category=PERFORMANCE"
Give it a try this way
I'm trying to detect the current web browser within one of my Api Controllers in my program using MVC4. Everywhere I look people say to use Request.Browser, however I can't get that to work. Any suggestions or is there something I'm overlooking?
You can use the HttpBrowserCapabilities in System.Web like this
var userAgent = HttpContext.Current.Request.UserAgent;
var userBrowser = new HttpBrowserCapabilities { Capabilities = new Hashtable { { string.Empty, userAgent } } };
var factory = new BrowserCapabilitiesFactory();
factory.ConfigureBrowserCapabilities(new NameValueCollection(), userBrowser);
//Set User browser Properties
BrowserBrand = userBrowser.Browser;
BrowserVersion = userBrowser.Version;
This relies on browscap.ini in Windows/System32/inetsrv/ or Windows/SysWOW64/inetsrv for definitions.
This article may also help - http://stephenwalther.com/archive/2010/03/05/use-asp-net-4-browser-definitions-with-asp-net-3-5
You could do something like following too from within the Web API's action:
System.Net.Http.HttpRequestMessage currentRequest = this.Request;
System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductInfoHeaderValue> userAgentHeader = currentRequest.Headers.UserAgent;
I'm trying to implement a pure WCF scenario where I want to call Dynamics CRM WCF service without relying on the SDK helper classes. Basically, I would like to implement federated authentication against Dynamics CRM 2011 using only native WCF support from the .net framework.
The reason I'm doing this is that I would like to port this scenario later-on to BizTalk.
I've successfully generated proxy classes with SvcUtil, but the part of the policies and security assertions are not compatible with the configuration schema. SvcUtil suggests to build the binding from code instead, which is what I'm trying to do.
The resulting code is here:
private static void CallWcf()
{
OrganizationServiceClient client = null;
try
{
// Login Live.com Issuer Binding
var wsHttpBinding = new WSHttpBinding();
wsHttpBinding.Security = new WSHttpSecurity();
wsHttpBinding.Security.Mode = SecurityMode.Transport;
// Endpoint Binding Elements
var securityElement = new TransportSecurityBindingElement();
securityElement.DefaultAlgorithmSuite = SecurityAlgorithmSuite.TripleDes;
securityElement.IncludeTimestamp = true;
securityElement.KeyEntropyMode = SecurityKeyEntropyMode.CombinedEntropy;
securityElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
securityElement.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
var securityTokenParameters = new IssuedSecurityTokenParameters();
securityTokenParameters.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;
securityTokenParameters.ReferenceStyle = SecurityTokenReferenceStyle.Internal;
securityTokenParameters.RequireDerivedKeys = false;
securityTokenParameters.TokenType = null;
securityTokenParameters.KeyType = SecurityKeyType.SymmetricKey;
securityTokenParameters.KeySize = 192;
securityTokenParameters.IssuerAddress = new EndpointAddress("https://login.live.com/extSTS.srf");
securityTokenParameters.IssuerMetadataAddress = null;
securityTokenParameters.DefaultMessageSecurityVersion = null;
securityTokenParameters.IssuerBinding = wsHttpBinding;
securityElement.EndpointSupportingTokenParameters.Signed.Add(securityTokenParameters);
var textMessageEncodingElement = new TextMessageEncodingBindingElement();
textMessageEncodingElement.MaxReadPoolSize = 64;
textMessageEncodingElement.MaxWritePoolSize = 16;
textMessageEncodingElement.MessageVersion = MessageVersion.Default;
textMessageEncodingElement.WriteEncoding = System.Text.Encoding.UTF8;
textMessageEncodingElement.ReaderQuotas.MaxStringContentLength = 8192;
textMessageEncodingElement.ReaderQuotas.MaxArrayLength = 16384;
textMessageEncodingElement.ReaderQuotas.MaxBytesPerRead = 4096;
textMessageEncodingElement.ReaderQuotas.MaxNameTableCharCount = 16384;
var httpsTransportElement = new HttpsTransportBindingElement();
httpsTransportElement.ManualAddressing = false;
httpsTransportElement.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
CustomBinding binding = new CustomBinding();
binding.Elements.Add(securityElement);
binding.Elements.Add(textMessageEncodingElement);
binding.Elements.Add(httpsTransportElement);
client = new OrganizationServiceClient(binding, new EndpointAddress(EndpointUri));
client.ClientCredentials.UserName.UserName = Username;
client.ClientCredentials.UserName.Password = Password;
client.Open();
var columnSet = new schemas.microsoft.com.xrm._2011.Contracts.ColumnSet();
var identifier = new Guid("fbf8240e-2c85-e011-ad55-1cc1de0878eb");
columnSet.Columns = new string[] { "name" };
var entity = client.Retrieve("account", identifier, columnSet);
}
finally
{
if (client != null)
client.Close();
}
}
I'm new to federated authentication and am having a hard time figuring out the potential differences between the many available bindings, so I would be grateful for any help in this regard.
It is probably possible, but hugely complicated. We had a project using Dynamics which moved to ADFS, and required adding lots of extra code around refreshing tokens (code form autorefreshsecuritytoken.cs, deviceidmanager.cs and toolserviceproxies.cs from the SDK) and that was still using the SDK for everything.
Bare in mind you also need windows.identification installed in the OS which is another load of functionality to copy.
In the end you can always just use JustDecompile or similar to see what the SDK is doing.
Web service is created in PHP im calling by adding a reference in C#
funcRequest aa = new funcRequest();
aa.param = "ZZ";
string z;
funcResponse a = new funcResponse();
z = a.result;
i created like this to call the web service from C# but looks its not giving any value back .. where am i wrong ?
You shouldn't be creating the response object yourself. You should be doing something like:
FuncRequest request = new FuncRequest("ZZ");
MyWebService service = new MyWebService();
FuncResponse response = service.DoSomething(request);
Obviously the exact details will depend on how you're connecting to the service, whether you're generating the proxy code etc, but basically you need to get something involved which represents the service itself.
You'll need to instantiate and make requests with the generated client proxy class or something similar, you can't just new up requests and responses and in this manner, you need to use and retrieve them, respectively. For instance, if your service reference was named MyService then you ought to have a MyServiceClient class available to you, so that:
using (var myServiceClient = new MyServiceClient())
{
var request = new MyServiceRequestType();
request.MyProperty = "zzz";
var response = myServiceClient.MakeRequest(request);
}