Setting proxy for Google Analytics Data API (GA4) - c#

I need to config proxy credential for GA4 Client library to pass it from http proxy server, unfortunately there isn't any rich documentation for this purpose on the web (or maybe I couldn't find them)
Google Analytics Data API(GA4)
using Google.Analytics.Data.V1Beta;
using System.Net;
// Config Proxy Credential
WebProxy proxy = new WebProxy([proxy_url], [bypass]);
proxy.Credentials = new NetworkCredential([username], [password]);
// Google Analytics configuration
BetaAnalyticsDataClient client = BetaAnalyticsDataClient.Create();
RunReportRequest request = new RunReportRequest
{
Property = "properties/" + propertyId,
Dimensions = { new Dimension{ Name="city"}, },
Metrics = { new Metric{ Name="activeUsers"}, },
DateRanges = { new DateRange{ StartDate="2020-03-31", EndDate="today"}, },
};
// Make the request
var response = client.RunReport(request);
I have tried to assign object proxy to BetaAnalyticsDataClient or RunReportRequest object but I can't find it and I don't know how to use proxy configuration for GA4 library.

Related

Salesforce Pub/Sub client in .NET

I would like to subscript to a Salesforce platform event. I am trying to create a client in C#/.NET for a Salesforce Pub/Sub API. There are examples in other languages but not in .NET : https://github.com/developerforce/pub-sub-api
I am using the Grpc.Net.Client nuget packages.
var topicName = "/event/SomeEvent__e";
var pubSubEndpoint = "https://api.pubsub.salesforce.com:7443";
var accessToken = "xxxx";
var organisationId = "xxxx";
var instanceUrl = "https://xxxxx.sandbox.my.salesforce.com";
var credentials = CallCredentials.FromInterceptor((c, m) =>
{
m.Add("accesstoken", accessToken);
m.Add("instanceurl", instanceUrl);
m.Add("tenantid", organisationId);
return Task.CompletedTask;
});
var options = new GrpcChannelOptions
{
Credentials = ChannelCredentials.Create(new SslCredentials(), credentials)
};
var channel = GrpcChannel.ForAddress(pubSubEndpoint, options);
var client = new PubSub.PubSubClient(channel);
var topicRequest = new TopicRequest()
{
TopicName = topicName
};
var topic = client.GetTopic(topicRequest);
I know my credentials are correct because I can use postman to hit the oauth2 endpoint and get a valid access token. But when I try and call a client method like client.GetTopic, then I get the following error.
Status(StatusCode="PermissionDenied", Detail="An error occurred while getting the metadata for org CORE/prod/00DN0000000c8Hk and topic /event/SomeEvent__e. Ensure the credentials and topic name are correct. rpcId: 21d854fb-17dc-4778-9524-6264bd1a920d")
Am I setting up the credentials object wrong? I cannot find any example of subscribing to a Salesforce Pub/Sub in .NET.

C# WCF Service Get Status Code in Client from One way Service

I have a WCF service which has a method named ArchiveFile(string fileName) which basically archives files. I have created a proxy project using svcutil and added its reference created in my client application and is consuming the service as follows:
var binding = new WSHttpBinding { Security = new WSHttpSecurity() { Mode = SecurityMode.None } };
var address = new EndpointAddress(this.TargetUrl);
var fileService = new FileServiceClient(binding, address);'
I want to know how do I determine the Http Status Code (200 - OK or any other) for the WCF Service call.
We can get the http status code through WebOperationContext Class:
WebOperationContext statuscode = WebOperationContext.Current;
Console.WriteLine(statuscode.OutgoingResponse.StatusCode);
For more information about WebOperationContext,please refer to the following link:
https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.web.weboperationcontext?view=netframework-4.8

How to configure client? AWS Elasticsearch request C#

I am new to Amazon Web Services.
I configured domain to use ElasticSearch in AWS(Amazon Web Services) console. Confirured usage of Http Requests.
Went through documantation of creating ElasticSearch client from
https://www.elastic.co/guide/en/elasticsearch/client/net-api/1.x/security.html
var response = client.RootNodeInfo(c => c
.RequestConfiguration(rc => rc
.BasicAuthentication("UserName", "Password")
));
Works fine to me (Response is 200)
But when i try to configure authentication credentials like this and pass config to client constructor i need to have "cloudId" i didnt find in at AWS where sould i search for it? or what i have to do?
My client code:
BasicAuthenticationCredentials credentials = new BasicAuthenticationCredentials("UserName", "Password");
var config = new ConnectionSettings("cloudId???", credentials);
var client = new ElasticClient(config);
var response = client.Ping();
I recently did this but a different way. I used the Nuget package AwsSignatureVersion4 and an IAM user with appropriate permissions to the ElasticSearch service.
But basically, use the ImmutableCredentials and just do what I need to do via the REST calls and the C# HttpClient. I find it easier than using the .NET ElasticSearch library. I can then copy/paste back and forth from Kibana.
var credentials = new ImmutableCredentials("access_key", "secret_key", null);
HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(someObjOrQuery), Encoding.UTF8);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var resp = httpClient.PostAsync(es_url,
httpContent,
regionName: "us-east-1",
serviceName: "es",
credentials: credentials).GetAwaiter().GetResult();
if(resp.IsSuccessStatusCode)
{
//Good to go
}
else
{
//this gets what ES sent back
var content = response.Content.ReadAsStringAsync();
dynamic respJson = JObject.Parse(content.Result());
//Now you can access stuff by dot and it's dynamic respJson.something
}

How do I send basic authentication credentials for a prem wcf https service over azure relay C#?

I have a WebAapp on Azure that sends a request to Azure Relay. It should transfer to a listener on premises WCF HTTPS service hosted on IIS that requires basic authentication. How do I send authorization basic header for the onprem WCF service over the Azure Relay . How do I send ? example,
"Authorization": "Basic 239837987XYC"
I have used channel factory,
var ChannelFactory<Overview.MyChannel> cf;
var relayNamespace ="myrelaynamespace";
var relayListener = "myrelaylistener";
var endPointAddress = new EndpointAddress(ServiceBusEnvironment.CreateServiceUri("https", relayNamespace, relayListener));
cf = new ChannelFactory<Overview.ItServiceManagementAOChannel>(binding, endPointAddress);
ClientCredentials loginCredentials = new ClientCredentials();
loginCredentials.UserName.UserName = "onpremWCFusername";
loginCredentials.UserName.Password = "onpremWCFpassword";
cf.Endpoint.Behaviors.Add(new TransportClientEndpointBehavior
{
TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(ConfigurationManager.AppSettings.Get("WcfRelayKeyName"), ConfigurationManager.AppSettings.Get("WcfRelayKey"))
});
cf.Endpoint.Behaviors.Add(loginCredentials);
I get the Error: The value could not be added to the collection, as the collection already contains an item of the same type: 'System.ServiceModel.Description.ClientCredentials'. This collection only supports one instance of each type.
Parameter name: item
using (var ch = cf.CreateChannel())
{
try
{
var resp = ch.CreateTaskAsync(req).Result;
}
}
Try to specify the windows credential as client credential.
factory.Credentials.Windows.ClientCredential.UserName = "administrator";
factory.Credentials.Windows.ClientCredential.Password = "123456";
IService sv = factory.CreateChannel();
Feel free to let me know if the problem still exists.

Send web header collection

How to send web header collection from rest Service to remoting service?
I have tried to send web headers using below code but its not working.
System.Net.WebRequest request = base.GetWebRequest(uri);
request.Headers.Add("myheader", "myheader_value");
You can try the below sample
public RemotingServiceClient serviceClient = new RemotingServiceClient();
public void Demo()
{
using (OperationContextScope scope = new OperationContextScope(serviceClient.InnerChannel))
{
MessageHeader<string> header = new MessageHeader<string>("HeaderValue1");
var v1 = header.GetUntypedHeader("HeaderName1", "RemotingService");
OperationContext.Current.OutgoingMessageHeaders.Add(v1);
header = new MessageHeader<string>("HeaderValue2");
var v2 = header.GetUntypedHeader("HeaderName2", "RemotingService");
OperationContext.Current.OutgoingMessageHeaders.Add(v2);
//IMP: To send headers make sure to call service in this block only.
//Keep unique uri name "RemotingService"
return serviceClient.MyRemotingServiceCall();
}
}
It's working for me as expected

Categories

Resources