How to push single commit to remote branch libgit2sharp - libgit2

I'm trying to push a single specific commit to a remote branch using LibGit2Sharp.
I'm looking for the equivalent of git push <remote name> <commit hash>:<remote branch name>
https://miteshshah.github.io/linux/git/how-to-push-single-commit-with-git/
Is there anything similar for LibGit2Sharp? Or is there a better approach for this?
Thanks,
Garrick

Have you looked at their documentation? According to that you should be able to use:
using (var repo = new Repository("path/to/your/repo"))
{
LibGit2Sharp.PushOptions options = new LibGit2Sharp.PushOptions();
options.CredentialsProvider = new CredentialsHandler(
(url, usernameFromUrl, types) =>
new UsernamePasswordCredentials()
{
Username = USERNAME,
Password = PASSWORD
});
repo.Network.Push(repo.Branches[BRANCHNAME], options);
}
Another variant, using Remote to push to the origin:
using (var repo = new Repository("path/to/your/repo"))
{
Remote remote = repo.Network.Remotes["origin"];
var options = new PushOptions();
options.CredentialsProvider = (_url, _user, _cred) =>
new UsernamePasswordCredentials { Username = "USERNAME", Password = "PASSWORD" };
repo.Network.Push(remote, #"refs/heads/master", options);
}

Related

How can I connect to S3 APS External Download?

I'm trying to access s3://aps-external-download using .NET SDK
var client = new AmazonS3Client(accessKey, secretKey, RegionEndpoint.USEast1);
var response = await client.ListObjectsAsync();
foreach (var x in response.S3Objects)
{
Console.WriteLine("{0}\t{1}", x.BucketName);
}
But I'm getting Access Denied
{Amazon.S3.AmazonS3Exception}
ErrorCode: AccessDenied
ErrorMessage: Access Denied
From aws CLI, I'm able to list the folders
aws s3 ls s3://aps-external-download/***/
PRE ***_report/
PRE ***_report/
I'm trying to find a solution from https://docs.aws.amazon.com/sdk-for-net/index.html documentation but it's not been helpful.
What could I be missing?
The problem is that I was using the wrong method.
var response = await client.GetObjectAsync("aps-external-download/path/to/the/report/1999-01-01", "report_file");
var reader = new StreamReader(response.ResponseStream);
while (!reader.EndOfStream)
{
Console.WriteLine(reader.ReadLine());
}

mautic - I want to add contact in mautic via api

I want to add contact in mautic via an API. Below I have the code, but it's not adding the contact in mautic.
I have installed mautic in localhost. Studied the API form in the mautic documentation and tried to do it for at least 2 days, but I am not getting any results on it.
<?php
// Bootup the Composer autoloader
include __DIR__ . '/vendor/autoload.php';
use Mautic\Auth\ApiAuth;
session_start();
$publicKey = '';
$secretKey = '';
$callback = '';
// ApiAuth->newAuth() will accept an array of Auth settings
$settings = array(
'baseUrl' => 'http://localhost/mautic', // Base URL of the Mautic instance
'version' => 'OAuth2', // Version of the OAuth can be OAuth2 or OAuth1a. OAuth2 is the default value.
'clientKey' => '1_1w6nrty8k9og0kow48w8w4kww8wco0wcgswoow80ogkoo0gsks', // Client/Consumer key from Mautic
'clientSecret' => 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c', // Client/Consumer secret key from Mautic
'callback' => 'http://localhost/mtest/process.php' // Redirect URI/Callback URI for this script
);
/*
// If you already have the access token, et al, pass them in as well to prevent the need for reauthorization
$settings['accessToken'] = $accessToken;
$settings['accessTokenSecret'] = $accessTokenSecret; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenExpires; //UNIX timestamp
$settings['refreshToken'] = $refreshToken;
*/
// Initiate the auth object
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
/*
if( $auth->getAccessTokenData() != null ) {
$accessTokenData = $auth->getAccessTokenData();
$settings['accessToken'] = $accessTokenData['access_token'];
$settings['accessTokenSecret'] = 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c'; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenData['expires']; //UNIX timestamp
$settings['refreshToken'] = $accessTokenData['refresh_token'];
}*/
// Initiate process for obtaining an access token; this will redirect the user to the $authorizationUrl and/or
// set the access_tokens when the user is redirected back after granting authorization
// If the access token is expired, and a refresh token is set above, then a new access token will be requested
try {
if ($auth->validateAccessToken()) {
// Obtain the access token returned; call accessTokenUpdated() to catch if the token was updated via a
// refresh token
// $accessTokenData will have the following keys:
// For OAuth1.0a: access_token, access_token_secret, expires
// For OAuth2: access_token, expires, token_type, refresh_token
if ($auth->accessTokenUpdated()) {
$accessTokenData = $auth->getAccessTokenData();
echo "<pre>";
print_r($accessTokenData);
echo "</pre>";
//store access token data however you want
}
}
} catch (Exception $e) {
// Do Error handling
}
use Mautic\MauticApi;
//use Mautic\Auth\ApiAuth;
// ...
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
$apiUrl = "http://localhost/mautic/api";
$api = new MauticApi();
$contactApi = $api->newApi("contacts", $auth, $apiUrl);
$data = array(
'firstname' => 'Jim',
'lastname' => 'Contact',
'email' => 'jim#his-site.com',
'ipAddress' => $_SERVER['REMOTE_ADDR']
);
$contact = $contactApi->create($data);
echo "<br/>contact created";
Any help will be appreciated.
use Curl\Curl;
$curl = new Curl();
$un = 'mayank';
$pw = 'mayank';
$hash = base64_encode($un.':'.$pw);
$curl->setHeader('Authorization','Basic '.$hash);
$res = $curl->post(
'http://mautic.local/api/contacts/new',
[
'firstname'=>'fn',
'lastname'=>'ln',
'email'=>'t1#test.com'
]
);
var_dump($res);
This is something very simple i tried and it worked for me, please try cleaning cache and enable logging, unless you provide us some error it's hard to point you in right direction. Please check for logs in app/logs directory as well as in /var/logs/apache2 directory.
In my experience sometimes after activating the API in the settings the API only starts working after clearing the cache.
Make sure you have activated the API in the settings
Clear the cache:
cd /path/to/mautic
rm -rf app/cache/*
Then try again
If this didn't work, try to use the BasicAuth example (You have to enable this I the settings again and add a new User to set the credentials)
I suspect that the OAuth flow might be disturbed by the local settings / SSL configuration.
these steps may be useful:
make sure API is enabled(yes I know it's might be obvious but still);
check the logs;
check the response body;
try to send it as simple json via Postman
it may be one of the following problems:
Cache;
You are not sending the key:value; of the required custom field;
you are mistaken with authentication;
Good luck :)

Printing spreadsheet to PDF then saving file in Drive using OAuth2

function topdf() {
var foldersave=DriveApp.getFolderById('0Byy1DdsfdfTQRnVlfb05wOV83T00')
var d= new Date()
var oauthConfig = UrlFetchApp.addOAuthService("google");
var scope = "https://docs.google.com/feeds/";
//make OAuth connection
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
//get request
var request = {
"method": "GET",
"oAuthServiceName": "google",
"oAuthUseToken": "always",
"muteHttpExceptions": true
};
var key='1QUj_OyHisdfsdfjwfNu1l-JuI528ev6FNRJv-oljIY';
var fetch='https://docs.google.com/spreadsheets/d/'+key+'/export?format=pdf&size=A4&portrait=false'
var name = "Timestamp for: "+ d + ".pdf";
var pdf = UrlFetchApp.fetch(fetch, request);
pdf = pdf.getBlob().setName(name);
var file = foldersave.createFile(pdf)
}
I'm looking for a step by step tutorial to convert the above code using OAuth2 . I'm having some problems migrating. I can find bits of code on OAuth2, but don't know how it ties together. The code was really simple before, now it seems to be much more complicated? Or am I missing something simple?
I've tried to replace the OAuth connection section but having trouble. https://github.com/googlesamples/apps-script-oauth2 it seems like the getDriveService should be used somehow?
You'll find a function that generates and saves PDFs for one or all of your sheets in
Convert all sheets to PDF with Google Apps Script.
For anyone who hadn't seen the notice posted in the cellar of the Local Planning Office 3 years ago, Google has deprecated OAuth1 & OAuth1a authorization for their services.
In their guide, Migrating from OAuthConfig to the OAuth1 library, the Apps Script team describes how to migrate your code from one to the other. What they fail to mention is that you don't need to.
There IS an easier way, at least for accessing Google's services.
You can obtain the OAuth 2.0 access token for the current user with ScriptApp.getOAuthToken(), which means a simplifying change in any script that previously used OAuthConfig.
To convert your script:
Replace
var request = {
"method": "GET",
"oAuthServiceName": "google",
"oAuthUseToken": "always",
"muteHttpExceptions": true
};
with
var request = {
"method": "GET",
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
},
"muteHttpExceptions": true
};
Delete every remaining reference to the old OAuthConfig class.
...
var oauthConfig = UrlFetchApp.addOAuthService("google");
var scope = "https://docs.google.com/feeds/";
//make OAuth connection
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
...
That's all there is to it.
Follow the migration guide if you're using an external (non-Google) service that requires OAuth 2.0 authentication.
And yes, even with the library it's more complicated than OAuth1 was - but necessarily so.
Here is the change. Because you are using DriveApp your script already has the authorization to access your files from any source including UrlFetchApp. All you have to do is get the token from the script and pass it in the header of your Fetch request.
function topdf() {
var foldersave=DriveApp.getFolderById('0Byy1DdsfdfTQRnVlfb05wOV83T00');
var d= new Date();
var request = {
"method": "GET",
"headers":{"Authorization": "Bearer "+ScriptApp.getOAuthToken()},
"muteHttpExceptions": true
};
var key='1QUj_OyHisdfsdfjwfNu1l-JuI528ev6FNRJv-oljIY';
var fetch='https://docs.google.com/spreadsheets/d/'+key+'/export?format=pdf&size=A4&portrait=false'
var name = "Timestamp for: "+ d + ".pdf";
var pdf = UrlFetchApp.fetch(fetch, request);
pdf = pdf.getBlob().setName(name);
var file = foldersave.createFile(pdf)
}

cordova/phonegap 3.3: how to set user credentials in fileUploadOptions

I'm trying to make a file upload via Phonegap 3.3 file transfer plugin to a windows server secured by base authentication. Actually the normal conversation between my app and the server (per ajax) is working perfectly by sending my user credentials with every ajax call.
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
options.headers = {
'Authorization':authHeaderValue(db.getItem("user"), db.getItem("pass"))
};
and
authHeaderValue = function(username, password) {
var tok = username + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
};
This is what I tried so far (I found it on stackoverflow thread) but it gives me back a 401-unauthorized...
Pls. give me a short reply if you know something that could help me.
Best regards to you all,
Ingmar
Well, I do something similar but instead of "Basic" I use JWT for authentication. I'll show you the code I use:
options.headers = { 'Authorization': 'Bearer ' + app.session.getSess('token') };
And I use SessionStorage to save the token while it is valid.
If you wanna know about JSON Web Token
Another thing, remember to change the headers in your server, in my case something like:
('Access-Control-Allow-Origin','*');
('Access-Control-Allow-Methods','GET,PUT,POST,DELETE,OPTIONS');
('Access-Control-Allow-Headers','Content-Type, Authorization, Content-Length, X-Requested-With');

dartlang and dartdap library and connection to active directory

I was looking for a good ldap library for Dart for connecting Microsoft Active Directory. I found dartdap, but I can't seem to get it working. I'm 100% shure that my CN and password is correct, because I can connect to Active directory for example with lpap browser.
The error I get is:
Uncaught Error: Invalid Credentials (49) msg=80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1
The ldap.yaml looks like this (address, password and username scrambled off course)
# LDAP configuration file
# default is used if no connection name is specified
default:
port: 389
host: xxx.xx.com
bindDN: cn=testaccount
password: xxxxxxxx
And the ldaptest.dart looks like this:
void readDataFromLDAPServer() {
var ldapConfig = new LDAPConfiguration("ldap.yaml","default");
var attrs = ["dn", "cn", "objectClass"];
var filter = Filter.substring("cn=A*");
var notFilter = Filter.not(filter);
ldapConfig.getConnection().then( (LDAPConnection ldap) {
ldap.search("dc=example,dc=com", filter, attrs).
listen( (SearchEntry entry) => print('Found $entry'));
// we expect to find non A entries
ldap.search("dc=example,dc=com", notFilter, attrs)
.listen( (SearchEntry entry) {
//print("Not search = ${entry}");
// todo: test entries.
});
});
}
Any idea, what might be wrong?
I am using the code below to successfully bind to a Microsoft AD server:
var host = "ip_address";
var ssl = false;
var port = null;
var bindDN = "accountname#domain.name";
var password = "password";
var connection = new LdapConnection(host: host);
connection.setProtocol(ssl, port);
connection.setAuthentication(bindDN, password);
Please note that my binding code differs from what you are using. I am also using an_ldap client for Dart 2.