How to use quick book invoice api in asp.net - c#

I have a requirement to integerate Quickbook api with my web application. I just created a sample application to accomplish it. I am strange to this I really dont have any idea about how to connect the api or to consume the api.I have mentioned the codes that i have took from ("https://developer.intuit.com/").
I tried by creating an app in the app manager, I have atttached the image FYR. After entering all those details i am not getting "accessTokenSecret" value. Here i just entered the apptoken valuea as accessToken value. Iam getting exception as "Unauthorized" in the service context line. Help me on this.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Intuit.Ipp.Core;
using Intuit.Ipp.Services;
using Intuit.Ipp.Data;
using Intuit.Ipp.Utility;
using Intuit.Ipp.Security;
using Intuit.Ipp.Data.Qbo;
using Newtonsoft.Json;
namespace QuickBookApiConsumption
{
public partial class Invoice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnsendInvoiceDetails_Click(object sender, EventArgs e)
{
string accessToke = "";
string appToken = "297db54bb5526b494dba97fb2a41063192cd";
string accessTokenSecret = "297db54bb5526b494dba97fb2a41063192cd";
string consumerKey = "qyprdMSG1YHpCPSlWQZTiKVc78dywR";
string consumerSecret = "JPfXE17YnCPGU9m9vuXkF2M765bDb7blhcLB7HeF";
string companyID = "812947125";
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(appToken, accessTokenSecret, consumerKey, consumerSecret);
ServiceContext context = new ServiceContext(oauthValidator, appToken, companyID, IntuitServicesType.QBO);
DataServices service = new DataServices(context);
Invoice os = new Invoice();
Intuit.Ipp.Data.Qbo.InvoiceHeader o = new Intuit.Ipp.Data.Qbo.InvoiceHeader();
o.CustomerName = "Viki";
o.CustomerId = new Intuit.Ipp.Data.Qbo.IdType { Value = "12" };
o.ShipMethodName = "Email";
o.SubTotalAmt = 3.00m;
o.TotalAmt = 6.00m;
o.ShipAddr = new Intuit.Ipp.Data.Qbo.PhysicalAddress { City = "Chni" };
}
}
}
Image:

You should check if you are using correct BASE URL
https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0400_quickbooks_online/0100_calling_data_services/0010_getting_the_base_url
Using some RESTClient[ ex - RestClient plugin of mozilla browser], verify the OAuth tokens.
Header(content-type) config window.
You can use the following
public void ConnectUsingAuth()
{
string accessToken = ConfigurationManager.AppSettings["AccessTokenQBD"];
string accessTokenSecret = ConfigurationManager.AppSettings["access-secret"];
string consumerKey = ConfigurationManager.AppSettings["consumerKey"];
string consumerKeySecret = ConfigurationManager.AppSettings["consumerSecret"];
string URI = "https://apiend-point";
WebRequest webRequest = WebRequest.Create(URI);
webRequest.Headers.Add("ContentType", "text/xml");
OAuthRequestValidator target = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerKeySecret);
}
Or [ Better option ] You can download the sample program from github and configure the web.config(with proper consumer key and secret)
https://developer.intuit.com/docs/0025_quickbooksapi/0055_devkits/sample_code
You can test all these API endpoints using APIExplorer tool.
Docs - https://developer.intuit.com/docs/0025_quickbooksapi/0010_getting_started/0007_firstrequest
ApiExplorer - https://developer.intuit.com/apiexplorer?apiname=V2QBO
Thanks

Related

CognitoUser does not contain a constructor that contain 4 arguments error and no definition for StartWithSrpAuthAsync at ASP.NET C#

I have been trying to use Cognito Sign In for my application at ASP.NET C# and I have managed to make the user sign up. However, when I am trying to implement the codes for Sign In there are 2 errors at these lines below :
CognitoUser user = new CognitoUser(username,ClientID,userPool,provider);
this line result in "CognitoUser does not contain a constructor that contain 4 arguments error"
and the 2nd error at this part :
authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
this line result in "CognitoUser does not contain definition for StartWithSrpAuthAsync and No Extension Method…accepting a first argument of type ” could be found" error
This is my full code :
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Amazon;
using Amazon.Runtime;
using Amazon.CognitoIdentity;
using Amazon.CognitoIdentityProvider;
using Amazon.CognitoIdentityProvider.Model;
using System.Threading.Tasks;
using System.Configuration;
using Amazon.Extensions.CognitoAuthentication;
namespace WebApplication2
{
public partial class WebForm5 : System.Web.UI.Page
{
const string PoolID = "poolid";
const string ClientID = "clientid";
static Amazon.RegionEndpoint Region = Amazon.RegionEndpoint.USEast1;
protected void Page_Load(object sender, EventArgs e)
{
string username = "user1";
string password = "pass";
string email = "email1";
SignInUser(username,password);
}
static async Task SignInUser(string username, string password)
{
AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), Region);
CognitoUserPool userPool = new CognitoUserPool(PoolID, ClientID, provider);
CognitoUser user = new CognitoUser(username,ClientID,userPool,provider);
InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
{
Password = password
};
AuthFlowResponse authResponse = null;
try
{
authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
}
catch(Exception ex)
{
Console.WriteLine("Logon Failed: {0}\n", ex.Message);
return;
}
GetUserRequest getUserRequest = new GetUserRequest();
getUserRequest.AccessToken = authResponse.AuthenticationResult.AccessToken;
}
}
Any help will be appreciated.
Thank You

Bing-Map-API what am I doing wrong?

I am trying for my school to use the Bing Map API and use GeocodeAdress. I build this application: http://msdn.microsoft.com/en-us/library/dd221354.aspx and the problem is I get this error every time.
it is at line 62: this method: GeocodeServiceClient geocodeService = new GeocodeServiceClient();
!InvalidOperationException was unhandled
An unhandled exception of type 'System.InvalidOperationException' occurred in System.ServiceModel.dll
Additional information: An endpoint configuration section for contract 'GeocodeService.IGeocodeService' could not be loaded because more than one endpoint configuration for that contract was found. Please indicate the preferred endpoint configuration section by name.
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BingMapsSample.GeocodeService;
using BingMapsSample.SearchService;
using BingMapsSample.ImageryService;
using BingMapsSample.RouteService;
namespace BingMapsSample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private String GeocodeAddress(string address)
{
string results = "";
string key = "Validate Bing Map Education Code";
GeocodeRequest geocodeRequest = new GeocodeRequest();
// Set the credentials using a valid Bing Maps key
geocodeRequest.Credentials = new GeocodeService.Credentials();
geocodeRequest.Credentials.ApplicationId = key;
// Set the full address query
geocodeRequest.Query = address;
// Set the options to only return high confidence results
ConfidenceFilter[] filters = new ConfidenceFilter[1];
filters[0] = new ConfidenceFilter();
filters[0].MinimumConfidence = GeocodeService.Confidence.High;
// Add the filters to the options
GeocodeOptions geocodeOptions = new GeocodeOptions();
geocodeOptions.Filters = filters;
geocodeRequest.Options = geocodeOptions;
// Make the geocode request
GeocodeServiceClient geocodeService = new GeocodeServiceClient();
GeocodeResponse geocodeResponse = geocodeService.Geocode(geocodeRequest);
if (geocodeResponse.Results.Length > 0)
results = String.Format("Latitude: {0}\nLongitude: {1}",
geocodeResponse.Results[0].Locations[0].Latitude,
geocodeResponse.Results[0].Locations[0].Longitude);
else
results = "No Results Found";
return results;
}
private string ReverseGeocodePoint(string locationString)
{
string results = "";
string key = "Validate Bing Map Education Code";
ReverseGeocodeRequest reverseGeocodeRequest = new ReverseGeocodeRequest();
// Set the credentials using a valid Bing Maps key
reverseGeocodeRequest.Credentials = new GeocodeService.Credentials();
reverseGeocodeRequest.Credentials.ApplicationId = key;
// Set the point to use to find a matching address
GeocodeService.Location point = new GeocodeService.Location();
string[] digits = locationString.Split(',');
point.Latitude = double.Parse(digits[0].Trim());
point.Longitude = double.Parse(digits[1].Trim());
reverseGeocodeRequest.Location = point;
// Make the reverse geocode request
GeocodeServiceClient geocodeService = new GeocodeServiceClient();
GeocodeResponse geocodeResponse = geocodeService.ReverseGeocode(reverseGeocodeRequest);
if (geocodeResponse.Results.Length > 0)
results = geocodeResponse.Results[0].DisplayName;
else
results = "No Results found";
return results;
}
private string SearchKeywordLocation(string keywordLocation)
{
String results = "";
String key = "Validate Bing Map Education Code";
SearchRequest searchRequest = new SearchRequest();
// Set the credentials using a valid Bing Maps key
searchRequest.Credentials = new SearchService.Credentials();
searchRequest.Credentials.ApplicationId = key;
//Create the search query
StructuredSearchQuery ssQuery = new StructuredSearchQuery();
string[] parts = keywordLocation.Split(';');
ssQuery.Keyword = parts[0];
ssQuery.Location = parts[1];
searchRequest.StructuredQuery = ssQuery;
//Define options on the search
searchRequest.SearchOptions = new SearchOptions();
searchRequest.SearchOptions.Filters =
new FilterExpression()
{
PropertyId = 3,
CompareOperator = CompareOperator.GreaterThanOrEquals,
FilterValue = 8.16
};
//Make the search request
SearchServiceClient searchService = new SearchServiceClient();
SearchResponse searchResponse = searchService.Search(searchRequest);
//Parse and format results
if (searchResponse.ResultSets[0].Results.Length > 0)
{
StringBuilder resultList = new StringBuilder("");
for (int i = 0; i < searchResponse.ResultSets[0].Results.Length; i++)
{
resultList.Append(String.Format("{0}. {1}\n", i + 1,
searchResponse.ResultSets[0].Results[i].Name));
}
results = resultList.ToString();
}
else
results = "No results found";
return results;
}
private void Geocode_Click(object sender, RoutedEventArgs e)
{
labelResults.Content = GeocodeAddress(textInput.Text);
}
private void ReverseGeocode_Click(object sender, RoutedEventArgs e)
{
labelResults.Content = ReverseGeocodePoint(textInput.Text);
}
private void Search_Click(object sender, RoutedEventArgs e)
{
labelResults.Content = SearchKeywordLocation(textInput.Text);
}
}
}
I found the solution line 62 should be:
var geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
Open your web.config file or app.config file. In there you will see a basic and custom binding configuration for the service. Remove the custom binding section. Clean and build your project and it should work.
As a side note. The Bing Maps SOAP services are really old and limited in functionality. They were released about 8 years ago. A newer REST based service was released about 4 years ago. REST is faster, has smaller response packages and has more features. You can find out more about the Bing Maps REST services here: http://msdn.microsoft.com/en-us/library/ff701713.aspx

Access User Info using Google APIs for .NET

I'm using the Google APIs Preview (1.7.0) to authorize a user via OAuth2. I've been following the sample MVC code. This is my implementation of FlowMetadata:
private static readonly IAuthorizationCodeFlow flow = ...; // Implementation of tokens
public static async Task<Google.Apis.Auth.OAuth2.Web.AuthorizationCodeWebApp.AuthResult> GetCredentials(Controller controller, CancellationToken cancellationToken) {
var result = await new AuthorizationCodeMvcApp(controller, new Models.Generic.AppFlowMetadata()).AuthorizeAsync(cancellationToken);
if (result.Credential != null)
{
// Struggling here. How do I make a request to get the e-mail address?
}
}
I now have a valid UserCredential and therefore Access Token, but I cannot find any managed APIs for accessing the user info. I did find this question, but this appears to assume I am just making raw requests, rather than using the official library.
How can I get the user's e-mail address?
You should do the following:
In addition to Google.Apis.Auth NuGet package you should install the following page: https://www.nuget.org/packages/Google.Apis.Oauth2.v2
Add Google.Apis.Oauth2.v2.Oauth2Service.Scope.UserinfoProfile and also Google.Apis.Oauth2.v2.Oauth2Service.Scope.UserinfoEmail to the scopes list (When you initialize the AppFlowMetadata).
Now, add the following code:
if (result.Credential != null)
{
var oauthSerivce = new Google.Apis.Oauth2.v2.Oauth2Service(
new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "OAuth 2.0 Sample",
});
var userInfo = await oauthSerivce.Userinfo.Get().ExecuteAsync();
// You can use userInfo.Email, Gender, FamilyName, ...
}
Set your scopes to:
https://www.googleapis.com/auth/userinfo.email
https://www.googleapis.com/auth/userinfo.profile
At: Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow.Scopes
And use this endpoint address: https://www.googleapis.com/oauth2/v1/userinfo?alt=json
That should help you to acquire the required information.
Here ,I edit my answere. Please look into this. On Default2.aspx page , I am displaying Session["username"] and Session["useremail"] value in label. I hope these will be help for you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
openIdAuth();
}
protected void openIdAuth()
{
OpenIdAjaxRelyingParty rp = new OpenIdAjaxRelyingParty();
var response = rp.GetResponse();
if (response != null)
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
NotLoggedIn.Visible = false;
Session["GoogleIdentifier"] = response.ClaimedIdentifier.ToString();
var fetchResponse = response.GetExtension<FetchResponse>();
Session["FetchResponse"] = fetchResponse;
var response2 = Session["FetchResponse"] as FetchResponse;
string UserName = response2.GetAttributeValue(WellKnownAttributes.Name.First) ?? "Guest"; // with the OpenID Claimed Identifier as their username.
string UserEmail = response2.GetAttributeValue(WellKnownAttributes.Contact.Email) ?? "Guest";
Session["username"] = UserName;
Session["useremail"] = UserEmail;
Response.Redirect("Default2.aspx");
break;
case AuthenticationStatus.Canceled:
lblAlertMsg.Text = "Cancelled.";
break;
case AuthenticationStatus.Failed:
lblAlertMsg.Text = "Login Failed.";
break;
}
}
var CommandArgument = "https://www.google.com/accounts/o8/id";
string discoveryUri = CommandArgument.ToString();
OpenIdRelyingParty openid = new OpenIdRelyingParty();
var url = new UriBuilder(Request.Url) { Query = "" };
var request = openid.CreateRequest(discoveryUri); // This is where you would add any OpenID extensions you wanted
var fetchRequest = new FetchRequest(); // to fetch additional data fields from the OpenID Provider
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.HomeAddress.Country);
request.AddExtension(fetchRequest);
request.RedirectToProvider();
}
}
Complete code to get UserProfile data.
var secrect = new ClientSecrets()
{
ClientId = "myClientId",
ClientSecret = "mySecret"
};
var scopes = new[] { Oauth2Service.Scope.UserinfoEmail, auth2Service.Scope.UserinfoProfile };
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(secrect, scopes, "user", CancellationToken.None).Result;
var oauthSerivce = new Oauth2Service(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "MyApplicationName",
});
var userInfo = oauthSerivce.Userinfo.Get().Execute();

Google Analytics API for .NET

I am trying to find a stable and up to date example of a Google Analytics Reporting handler in .NET. Any information on the matter will be greatly appreciated. I have searched, and found nothing that really is for current use in .NET. I have also noticed, that the friendly friend Google did not create a library for it, but did under Java. At least from what I was able to see. Does anyone have a reference I could view, or a link with some good examples of setting up a reporting tool with this API?
Thanks in advance. :)
Here is my basic working example I finally got. Hopefully this helps, enjoy!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Google.GData.Analytics;
using Google.GData.Client;
using Google.GData.Extensions;
namespace Gongos.AnalyticsAPI
{
public partial class _Default : Page
{
public string VisitsNumber()
{
string visits = string.Empty;
string username = "******** --> Your email";
string pass = "********** --> Your password";
string gkey = "?key= **** --> Your APY key <-- ****";
string dataFeedUrl = "https://www.google.com/analytics/feeds/data" + gkey;
string accountFeedUrl = "https://www.googleapis.com/analytics/v2.4/management/accounts" + gkey;
AnalyticsService service = new AnalyticsService("WebApp");
service.setUserCredentials(username, pass);
DataQuery query1 = new DataQuery(dataFeedUrl);
query1.Ids = "ga:********";
query1.Metrics = "ga:visits";
query1.Sort = "ga:visits";
query1.GAStartDate = new DateTime(2013, 1, 2).ToString("yyyy-MM-dd");
query1.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
query1.StartIndex = 1;
DataFeed dataFeedVisits = service.Query(query1);
foreach (DataEntry entry in dataFeedVisits.Entries)
{
string st = entry.Title.Text;
string ss = entry.Metrics[0].Value;
visits = ss;
}
return visits;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write("Visits:" + this.VisitsNumber());
}
}
}
}

Have you used Google's Directory API?

I'm trying to use Google Directory API Library for .NET to maintain email addresses for a domain. The latest library is google-admin-directory_v1-rev6-csharp-1.4.0-beta. The best and farthest I've gotten so far is to receive a 403 error (Not Authorized to access this resource/api).
Has anyone out there successfully used it? If so, could you share some code, tips, or tricks?
I have used it and got some success in creating a console-application.
At the moment I'm trying to find a way to skip the copy/paste of the authorization code.
Don't forget to turn on API access in your APIs Console.
I'll show you a small sample:
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Samples.Helper;
using Google.Apis.Services;
using Google.Apis.Util;
using Google.Apis.Admin.directory_v1;
using Google.Apis.Admin.directory_v1.Data;
namespace Bergstedts.CreateNewUser
{
public class Program
{
static void Main(string[] args)
{
// Display the header and initialize the sample.
CommandLine.EnableExceptionHandling();
Console.WriteLine("Create users in a google apps domain!");
Console.WriteLine("by Jonas Bergstedt 2013");
// Get the user data and store in user object
Console.Write("Email: ");
string userId = Console.ReadLine();
Console.Write("Givenname: ");
string GivenName = Console.ReadLine();
Console.Write("Familyname: ");
string FamilyName = Console.ReadLine();
Console.Write("Password: ");
string Password = Console.ReadLine();
User newuserbody = new User();
UserName newusername = new UserName();
newuserbody.PrimaryEmail = userId;
newusername.GivenName = GivenName;
newusername.FamilyName = FamilyName;
newuserbody.Name = newusername;
newuserbody.Password = Password;
// Register the authenticator.
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = "<your clientId from Google APIs Console>",
ClientSecret = "<your clientsecret from Google APIs Console>",
};
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
// Create the service.
var service = new DirectoryService(new BaseClientService.Initializer()
{
Authenticator = auth,
ApplicationName = "Create User",
ApiKey = "<your API Key from Google APIs console> (not sure if needed)"
});
User results = service.Users.Insert(newuserbody).Execute();
Console.WriteLine("User :" + results.PrimaryEmail + " is created");
Console.WriteLine("Press any key to continue!");
Console.ReadKey();
}
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
// Get the auth URL:
IAuthorizationState state = new AuthorizationState(new[] { DirectoryService.Scopes.AdminDirectoryUser.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
Console.WriteLine();
Console.Write("Authorization Code: ");
string authCode = Console.ReadLine();
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
}
}

Categories