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.
Related
I am rewriting an app that used Google Contacts API (RIP) to use People API. I already have a refresh token. Previously, I created an instance of the OAuth2Parameters object, and used it to create an instance of the RequestSettings class to be passed to the ContactsRequest constructor
OAuth2Parameters oparams = new OAuth2Parameters
{
AccessToken = tokenData.access_token,
RefreshToken = tokenData.refresh_token,
ClientId = ClientId,
ClientSecret = ClientSecret,
AccessType = "offline",
ApprovalPrompt = "force",
Scope = _contactScope
};
if (string.IsNullOrWhiteSpace(oparams.AccessToken))
{
oparams.AccessToken = "xyz"; //it doesn't matter what this token is, it just can't be blank, it will get refreshed
OAuthUtil.RefreshAccessToken(oparams);
dataStore._storedResponse.access_token = oparams.AccessToken;
}
var settings = new RequestSettings("My App")
{
OAuth2Parameters = oparams
};
if (paging)
{
settings.PageSize = 50;
settings.AutoPaging = true;
}
return new ContactsRequest(settings);
I cannot figure out how to do the same in the new world of People API. I obviously need to use PeopleServiceService object, but its constructor takes an instance of the Initializer object, and I don't know out how I can initialize it with the refresh token and (possibly) access token.
Here's the official tutorial on how to do authentication with the .NET library for all Google APIs:
https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth
Here's a useful snippet from it that will also help with persisting the refresh token to a file and use it in future authentication attempts:
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { BooksService.Scope.Books },
"user", CancellationToken.None, new FileDataStore("Books.ListMyLibrary"));
}
// Create the service.
var service = new BooksService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Books API Sample",
});
var bookshelves = await service.Mylibrary.Bookshelves.List().ExecuteAsync();
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¶m2=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;
I am new in Windows phone application development.
I have created my app in Google developer Console.
From my windows phone application I am using "webview" to render the Google login page and with successfull login I got a code like: 4/akd.........
Can anyone tell me how to access the code using "code" first time ?
I have try by following way :
public void GetProfileDetail(string code)
{
StringBuilder authLink = new StringBuilder();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
authLink.AppendFormat("code={0}", code);
authLink.AppendFormat("&client_id={0}", clientId);
authLink.AppendFormat("&client_secret={0}", clientSecret);
authLink.AppendFormat("&redirect_uri={0}", redirect_url);
authLink.Append("&grant_type=authorization_code");
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(authLink.ToString());
Stream os = null;
try // send the post
{
//webRequest.ContentLength = bytes.Length; // Count bytes to send
os = webRequest.GetRequestStreamAsync().Result;
os.Write(bytes, 0, bytes.Length); // Send it
}
catch (Exception ex)
{
}
}
but it gives me an error. Let me know what to do next
Thanks in advance.
You are trying to do the OAuth authentication through the webview, but that is not the recommended way to go.
Since wp8.1 there is a WebAuthenticationBroker class that you can use to initiate an OAuth process with a provider ( like Google in your case ).
A good detailed example can be found on MSDN here https://code.msdn.microsoft.com/windowsapps/Web-Authentication-d0485122
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.
I am trying to get a reference to a response stream before its complete in windows phone 8.
In other .Net platforms you can do
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(myUri);
WebResponse subscribeWebResponse = null;
Stream subscribeStream = null;
subscribeWebResponse = httpRequest.GetResponse();
subscribeStream = subscribeWebResponse.GetResponseStream();
For the purpose of creating Portable class libraries I've used the HttpClientLibrary from nuget.
This Adds ref to extensions assembly Microsoft.Net.Http
this allows me to return the async request at the time the headers have been read instead of waiting for the content transfer to be complete with
var clientResponse = await httpClient.SendAsync(requestmessage, HttpCompletionOption.ResponseHeadersRead);
The problem I'm having is that in windows phone 8 it doesn't work correctly, and still awaits the completion of the content stream to return.
Additionally
await httpWebRequest.BeginGetResponse(callback, request)
has the same behavior as these async methods are actually waiting for the completion of the web's response to continue execution.
So, is there any way to achieve the returning the response/stream at the point that i have received the response headers without Microsoft.Http.Net package?
Even if it has to be a Windows Phone 8 Platform Specific Solution?
Possibly an extension of HttpWebRequest?
From what I can tell, ResponseHeadersRead works on the WP8 emulator as it does on the desktop.
I installed the Win8 SDK. Created a windows phone app. I added this code to the MainPage ctor. This demonstrates a very rudimentary long polling example.
var client = new HttpClient();
var request = new HttpRequestMessage()
{
RequestUri = new Uri("http://oak:1001/longpolling")
};
client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, new CancellationToken())
.ContinueWith((t) =>
{
var response = t.Result;
response.Content.ReadAsStreamAsync()
.ContinueWith(s =>
{
var st = s.Result;
while (true)
{
var message= ReadNextMessage(st);
}
});
});
}
private static string ReadNextMessage(Stream stream)
{
int chr = 0;
string output = "";
while (chr != 10)
{
chr = stream.ReadByte();
output += Convert.ToChar(chr);
}
return output;
}
On my host dev machine I have a web api with a controller that looks like this...
public class LongPollingController : ApiController
{
public HttpResponseMessage Get()
{
Thread.Sleep(2000);
var content = new PushStreamContent( (s,c,t) =>
{
int i = 0;
while (true)
{
try
{
var message = String.Format("The current count is {0} " + Environment.NewLine, i++);
var buffer = Encoding.UTF8.GetBytes(message);
s.Write(buffer, 0, buffer.Length);
}
catch (IOException exception)
{
s.Close();
return;
}
Thread.Sleep(1000);
}
});
return new HttpResponseMessage(HttpStatusCode.OK)
{
RequestMessage = Request,
Content = content
};
}
}
So here's the deal. I would say that what you want to do is not possible, due to platform limitations... But SignalR has a WP client and is able to manage it. So it seems to me you have two options:
1) Dig into the SignalR source code to see how they do it (I'm on my phone right now so I can't provide a link).
UPDATE: Here is the link. They do some pretty neat tricks, like setting the Timeout to -1 for long-running clients. I think you should definitely use the techniques here.
OR
2) You can move whatever you're doing over to SignalR, which would gain the benefit of having a robust infrastructure and being cross-platform compatible.
HTH