2 step authentication C# Access JSON API via SSIS 2010 - ssis

I have managed in SSIS 2010 to access a JSON API with basic authentication ... Username and password, using the script below
I need to amend the script below to also include passing credentials of a Client Secret and Client ID
anyone know how to amend this for SSIS 2010. I have tried with no joy, so I have pasted the working code so far
Please help
WebRequest req = WebRequest.Create(#"https://sub.domain.com/api/operations? param=value&param2=value");
req.Method = "GET";
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String (Encoding.Default.GetBytes("username:password"));
//req.Credentials = new NetworkCredential("username", "password");
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

It may depend on how the API is set up and what it's expecting, but in my case, I did this in the creation of an HttpClientHandler:
using System.Net.Http;
using System.Configuration;
...
HttpClientHandler handler = new HttpClientHandler { Credentials = new NetworkCredential(ConfigurationManager.AppSettings["API.UserName"].ToString(), ConfigurationManager.AppSettings["API.Password"].ToString()) };
HttpClient apiClient = new HttpClient(handler);
OR, without using Configurations:
using System.Net.Http;
...
HttpClientHandler handler = new HttpClientHandler { Credentials = new NetworkCredential("MyUserName", "MyPassword") };
HttpClient apiClient = new HttpClient(handler);
Then use the Client to make calls. Here's how I do it:
HttpResponseMessage httpResponse = apiClient.GetAsync(curl).Result;

Related

Blazor webassembly http default header Forge Design Automation

Good morning,
I am trying to develop a webapp using Blazor and Net5. I have successfully implemented the 3 legged authentication system and attached the token to the default header for further requests.
I have implemented also the 2 legged authentication request in the same process and saved both in the local storage.
Now I need to start to call some Data Management service to store and retrieve models and also submit work items to design automation. All of these will require to send the bearer token together with the request.
I would like to manage this bit of the application on the server side and the question is: is there a way to use the token on the server side other then just try to retrieve that from the local storage?
Also, is is possible to setup two different HttpClient in the client app to be able to attach two different tokens and then use the same http client in the server-side Blazor? I assume I can not inject a service from the client to the server thou.
I can easily do it in the client side using DI
public async Task<string> PostSignedUrlAsync(string bucketKey, string objectKey)
{
using (var client = new HttpClient())
{
var token = await tokenManager.GetTwoFactorAsync();
using (var request = new HttpRequestMessage(
HttpMethod.Post,
$"https://{configurationManager.Host}/oss/v2/buckets/{bucketKey}/objects/{objectKey}/signed"
)
)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using (var response = await client.SendAsync(request))
{
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<PostObjectSigned>(json).SignedUrl;
}
}
return null;
}
}
}
public async Task PostTwoFactorAsync()
{
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(
HttpMethod.Post,
$"https://{configurationManager.Host}/authentication/v1/authenticate"
)
)
{
var body = $"client_id={configurationManager.ClientId}&client_secret={configurationManager.ClientSecret}&grant_type=client_credentials&scope={configurationManager.ScopesInternal}";
request.Content = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");
using (var response = await client.SendAsync(request))
{
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
TokenInternal = JsonConvert.DeserializeObject<Token>(json);
TokenInternal.ExpiresOn = DateTime.UtcNow.AddSeconds(TokenInternal.ExpiresIn) - TimeSpan.FromMinutes(10);
await localStorage.SetItemAsync(configurationManager.LocalStorageKeyInternal, TokenInternal);
}
}
}
}
}
Maybe is a simple question with a simple answer but I can't find any example that can explain how to solve this "connection" and there are now example in the Forge documentation around Blazor implementation that are suitable for this task.
Thanks in advance
Firstly, please don't call APIs from client side, send the token with only scope: viewables:read for viewing in forge viewer. Other than this, call all the forge APIs from server side. This is for security reasons. Because if you send and store tokens to client side, it's easy to get access to your resources for any client.
Regarding token scopes please refer these links:
Documentation
Tutorial

batch Google contact in dotnet

I cannot find any sample for batching contact insertions in dotnet.
We're using nuget package : Install-Package Google.GData.Contacts
For appointments we're batching in this way:
BatchRequest batch = new BatchRequest(service);
Google.Apis.Calendar.v3.EventsResource.InsertRequest ir = new EventsResource.InsertRequest(aservice, theEvent, userName);
batch.Queue<Google.Apis.Calendar.v3.Data.Event>(ir,
( error, i, message) =>
{
// code here
});
With the Google contacts apis, we do not find any InsertRequest object.
We're using the ContactRequest class for Oauth integration.
RequestSettings settings = new RequestSettings(ApplicationName);
string token = GetOauthAccessToken();
OAuth2Parameters oauth2 = new OAuth2Parameters();
oauth2.AccessToken = token;
settings.OAuth2Parameters = oauth2;
GetNextContactService = new ContactsRequest(settings);
Note: in the past, we were using the ContactService class with which we managed to batch inserts, but with this class we did not manage to attach an oauth token like in the code above.
old code:
PushContactService = new ContactsService("MigrationAsAService");
GOAuthRequestFactory requestFactory = new GOAuthRequestFactory("cl", "theappname");
requestFactory.ConsumerKey = this.ConnectorSettings.ConsumerKey;
requestFactory.ConsumerSecret = this.ConnectorSettings.ConsumerSecret;
PushContactService.RequestFactory = requestFactory;
ContactsFeed feed = new ContactsFeed(
new Uri(PushContactsURI),
PushContactService
);
feed.BatchData = new GDataBatchFeedData();
feed.BatchData.Type = GDataBatchOperationType.insert;
You should be able to use the ContactsService class with OAuth2, by creating a GOAuth2RequestFactory and setting that as the service's request factory.

Google and .Net windows console progeam

I need to write a windows console program that will take the results from a SQL query, and dump the results into a excel sheet. We are moving away from Microsoft, and towards Google technology. So I need to create a worksheet, dump the results in that file, and store on drive.
Is the sdk the best way to go on this? Am I going to need the SDK for Drive and for Worksheetes? I also need to have the console run on it's own, no user interaction at all. I have been working with this sample below, and got it to work. I'm not sure if I'm going in the right direction with this. Any advice would be great!
using System;
using System.Threading;
using System.Threading.Tasks;
using Google;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
using Google.Apis.Services;
using Google.Apis.Discovery;
using Google.GData.Client;
using Google.GData.Extensions;
namespace GoogleDriveSamples
{
class DriveCommandLineSample
{
static void Main(string[] args)
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "xxxxxxxxxx-bn0vi796pn7tog7utb9pt6pmptl8cpsq.apps.googleusercontent.com",
ClientSecret = "FwuyHxBAj2Z1",
},
new[] { DriveService.Scope.Drive },
"user",
CancellationToken.None).Result;
// Create the service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Credit Q",
});
File body = new File();
body.Title = "My document";
body.Description = "A test document";
body.MimeType = "text/plain";
byte[] byteArray = System.IO.File.ReadAllBytes("FTP.txt");
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain");
request.Upload();
File file = request.ResponseBody;
Console.WriteLine("File id: " + file.Id);
Console.WriteLine("Press Enter to end this process.");
Console.ReadLine();
}
}
}
You can do it in google apps script in about 5 lines of code.
Lok at the official samples. Basically use spreadsheetApp and jdbc.

HttpClient dosen't get data after update WP8

I have this code to get JSON data from an API for WP8:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(mainURL.ToString());
HttpResponseMessage response = await client.GetAsync("");
string res = await response.Content.ReadAsStringAsync();
var root = await JsonConvert.DeserializeObjectAsync<Rootobject>(res);
Everything works perfectly, but when I update data on the web API from the web site and try to retrieve data again using this code it gets the old data even though accessing the URL in a browser it gets the new data.
When I debug line by line, I see that the "response" object contains the old data.
The only way I have found to fix this is to rebuild the project in this way it works.
How can I properly get the updated data?
There may be some caching involved. Tried adding some random string to the URL, like
client.BaseAddress = new Uri(mainURL.ToString()+"&random="+DateTime.Now.Ticks);
I have same kind of problem. I tried this this may be help you.
HttpWebRequest request = HttpWebRequest.CreateHttp(mainURL.ToString());
request.Method = "GET or Post";
request.BeginGetResponse(ResponseCallBack, request);
void ResponseCallBack(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
using (Stream data = response.GetResponseStream())
{
using (var reader = new StreamReader(data))
{
string jsonString = reader.ReadToEnd();
MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(Rootobject));
Rootobject yourdata= dataContractJsonSerializer.ReadObject(memoryStream) as Rootobject;
}
}
}

Seeing the Http Response content in ServiceStack

I am using ServiceStack to create a C# client to a JSON RESTful service. I have this code that returns my DTO:
Search result = restClient.Get (search);
This works fine, but in order to effectively debug the search results coming back I need to output the text content from the underlying HTTP Response object. (I don't know all the elements in the response yet in order to add them to the DTO).
Is there any way I can get hold of the underlying HTTP response, and thus the full text content, from my result object?
Thanks in advance.
#adamfowleruk
When inheriting from ServiceStack's built-in Service you can access the underlying Request and Response directly from the Response class with:
public class MyService : Service
{
public object Get(Request request)
{
base.Request ...
base.Response ...
}
}
You won't see the response output in your service or filters since it writes directly to the response stream and is the last thing that ServiceStack does after executing your service and all response filters.
For diagnosing HTTP I recommend using Fiddler or WebInspector also ServiceStack's built-in Request Logger might help as well.
Consuming a ServiceStack service
If you're using the C# Service Clients you can simply ask for what you want, e.g. you can access the returned response as a raw string:
string responseJson = client.Get<string>("/poco/World");
Or as raw bytes:
byte[] responseBytes = client.Get<byte[]>("/poco/World");
Or as a Stream:
using (Stream responseStream = client.Get<Stream>("/poco/World")) {
var dto = responseStream.ReadFully().FromUtf8Bytes().FromJson<PocoResponse>();
}
Or even access the populated HttpWebResponse object:
HttpWebResponse webResponse = client.Get<HttpWebResponse>("/poco/World");
webResponse.Headers["X-Response"] //World
using (webResponse)
using (var stream = webResponse.GetResponseStream())
using (var sr = new StreamReader(stream)) {
string response = sr.ReadToEnd();
}
You can also introspect the HttpWebResponse by using Global and Local Response filters, e.g:
JsonServiceClient.HttpWebResponseFilter = httpRes => { .. };
Or using a Local filter:
var client = new JsonServiceClient(baseUrl) {
ResponseFilter = httpRes => { .. }
};
Consuming a 3rd Party Service
If you're consuming a 3rd Party REST/HTTP API you can use a responseFilter: in ServiceStack's HTTP Util extensions:
List<GithubRepo> repos = "https://api.github.com/users/{0}/repos".Fmt(user)
.GetJsonFromUrl(responseFilter: httpRes => {
var remaining = httpRes.Headers["X-Api-Remaining"];
})
.FromJson<List<GithubRepo>>();
I use Fiddler to debug my services. It gives you all sorts of cool HTTP debugging facilities.
http://www.fiddler2.com/fiddler2/
I like to use RestConsole. It is a Chrome Extension and you can easily submit POST requests and see the response. It is also handy to create sample data and then step into the ServiceStack code and see what's happening. The ServiceStack PluralSight course has a nice demo of how to use them together.
Thanks to the above help I found the right answer. Documenting here for others:-
SearchResponse result = null; // my ServiceStack DTO
HttpWebResponse webResponse = restClient.Get<HttpWebResponse>(
completePath("/v1/search",qp)); // builds the URL with parameters
using (var stream = webResponse.GetResponseStream())
using (var sr = new StreamReader(stream)) {
var text = sr.ReadToEnd();
log.log ("response text: " + text); // *** PRINTING STRING VALUE HERE FOR DEBUG
result = text.FromJson<SearchResponse>();
}
// Now do something useful with the result DTO object
log.log ("RESULT: " + result.ToString ());
for (int i = 0; i < result.Results.Length; i++) {
log.log ("Result " + i + ": " + result.Results[i].ToString());
}