I trying using Google Analytics with C# to get stats information to display in my webiste
Here is my code
public ActionResult Index()
{
string userName = "admin#email.com";
string passWord = "mypass";
string profileId = "ga:xxxxxxxx";
string key = "2d751338cb092ef8da65f716e37a48604386c9sw";
string dataFeedUrl = "https://www.google.com/analytics/feeds/data"+key;
var service = new AnalyticsService("API Project");
service.setUserCredentials(userName, passWord);
var dataQuery = new DataQuery(dataFeedUrl)
{
Ids = profileId,
Metrics = "ga:pageviews",
Sort = "ga:pageviews",
GAStartDate = new DateTime(2010, 3, 1).ToString("yyyy-MM-dd"),
GAEndDate = DateTime.Now.ToString("yyyy-MM-dd")
};
var dataFeed = service.Query(dataQuery);
var totalEntry = dataFeed.Entries[0];
ViewData["Total"] = ((DataEntry)(totalEntry)).Metrics[0].Value;
dataQuery.GAStartDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
dataQuery.GAEndDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
dataFeed = service.Query(dataQuery);
var yesterdayEntry = dataFeed.Entries[0];
ViewData["Yesterday"] = ((DataEntry)(yesterdayEntry)).Metrics[0].Value;
dataQuery.GAStartDate = DateTime.Now.ToString("yyyy-MM-dd");
dataQuery.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
dataFeed = service.Query(dataQuery);
var todayEntry = dataFeed.Entries[0];
ViewData["Today"] = ((DataEntry)(todayEntry)).Metrics[0].Value;
return View(dataFeed.Entries);
}
But when i run the code it always said "{"Invalid credentials"}"
Not sure why i facing this error while i checked many time about the key,username,password and profileId
Anyone facing this problem,can help me?
Many thanks
I think that your url is wrong. try in this way (you are missing ?key=).
string dataFeedUrl = "https://www.google.com/analytics/feeds/data?key="+key;
refer this google example where there is this example that should help you
public DataFeedExample()
{
// Configure GA API.
AnalyticsService asv = new AnalyticsService("gaExportAPI_acctSample_v2.0");
// Client Login Authorization.
asv.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS);
// GA Data Feed query uri.
String baseUrl = "https://www.google.com/analytics/feeds/data";
DataQuery query = new DataQuery(baseUrl);
query.Ids = TABLE_ID;
query.Dimensions = "ga:source,ga:medium";
query.Metrics = "ga:visits,ga:bounces";
query.Segment = "gaid::-11";
query.Filters = "ga:medium==referral";
query.Sort = "-ga:visits";
query.NumberToRetrieve = 5;
query.GAStartDate = "2010-03-01";
query.GAEndDate = "2010-03-15";
Uri url = query.Uri;
Console.WriteLine("URL: " + url.ToString());
// Send our request to the Analytics API and wait for the results to
// come back.
feed = asv.Query(query);
}
refer also this guide to configure your project
Also follow this guide to use OAuth 2.0
Related
I am trying to get the list of users in ADO using .NET clients. I am referring to this git repository:
https://github.com/microsoft/azure-devops-dotnet-samples/blob/master/ClientLibrary/Quickstarts/dotnet/GraphQuickStarts/Samples/EnumerateUsers.cs
I tried same thing but still it shows error that GetUsersAsync needs assembly reference. I have tried all the references. I am getting GetUserAsync but that is for one user. I need to fetch all the users.
Instead of using GetUsersAsync, please use ListUsersAsync:
PagedGraphUsers users = graphClient.ListUsersAsync().Result;
In the following two code samples i'm returning the users' emails. You can use Azure DevOps' userentitlements to return the information you need like the license details.
SDK
//string organization = ...
//string userName = ...
//string pat = ...
List<string> users = new List<string>();
var uri = new Uri($"https://vsaex.dev.azure.com/{organization}");
var credentials = new VssBasicCredential(userName, pat);
using (var connection = new VssConnection(uri, credentials))
using (var client = connection.GetClient<MemberEntitlementManagementHttpClient>())
{
string continuationToken = null;
do
{
var data = await client.SearchUserEntitlementsAsync(continuationToken);
continuationToken = data.ContinuationToken;
foreach (var member in data.Members)
{
string email = member.User.MailAddress.ToLower();
users.Add(email);
}
}
while (continuationToken != null);
}
Rest API
//string organization = ...
// HttpClient client = ...
List<string> users = new List<string>();
string baseUrl = $"https://vsaex.dev.azure.com/{organization}/_apis/userentitlements?api-version=6-preview.3";
string url = baseUrl;
string continuationToken = string.Empty;
do
{
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
dynamic data = await response.Content.ReadAsAsync<object>();
foreach (var member in data.members)
{
users.Add(member.user.mailAddress.ToString());
}
continuationToken = HttpUtility.UrlEncode(data.continuationToken.ToString());
url = baseUrl + "&continuationToken=" + continuationToken;
}
}
while (!string.IsNullOrWhiteSpace(continuationToken));
I am trying to submit a Credit Card Payment using the QuickBooks Online SDK, but when I run my code I get the following error:
Raw Credit Card Number not supported. Tokenized Credit Card Number
Required
Here is what I have. Can anyone explain how I can tokenize the card number using sdk before using it in this manner?
public Payment PaymentCreditCard(Order order, ServiceContext qboContextoAuth)
{
Payment payment = new Payment();
payment.TxnDate = Convert.ToDateTime(order.DateCreated);
payment.TxnDateSpecified = true;
Account depositAccount = Helper.FindOrAddAccount(qboContextoAuth, AccountTypeEnum.Bank, AccountClassificationEnum.Asset);
payment.DepositToAccountRef = new ReferenceType()
{
name = depositAccount.Name,
Value = depositAccount.Id
};
PaymentMethod paymentMethod = Helper.FindOrAdd<PaymentMethod>(qboContextoAuth, new PaymentMethod());
payment.PaymentMethodRef = new ReferenceType()
{
name = paymentMethod.Name,
Value = paymentMethod.Id
};
Customer customer = Helper.FindOrAdd<Customer>(qboContextoAuth, new Customer());
payment.CustomerRef = new ReferenceType()
{
name = customer.DisplayName,
Value = customer.Id
};
payment.PaymentType = PaymentTypeEnum.CreditCard;
CreditCardPayment creditCardPayment = new CreditCardPayment();
CreditChargeInfo creditChargeInfo = new CreditChargeInfo();
creditChargeInfo.BillAddrStreet = order.BillingAddress;
creditChargeInfo.CcExpiryMonth = Convert.ToInt32(order.CCExpMonth);
creditChargeInfo.CcExpiryMonthSpecified = true;
creditChargeInfo.CcExpiryYear = Convert.ToInt32(order.CCExpYear);
creditChargeInfo.CcExpiryYearSpecified = true;
creditChargeInfo.CCTxnMode = CCTxnModeEnum.CardNotPresent;
creditChargeInfo.CCTxnModeSpecified = true;
creditChargeInfo.CCTxnType = CCTxnTypeEnum.Charge;
creditChargeInfo.CCTxnTypeSpecified = true;
//reditChargeInfo.CommercialCardCode = "Cardcode" + Helper.GetGuid().Substring(0, 5);
creditChargeInfo.NameOnAcct = order.BillingName;
creditChargeInfo.Number = order.CCNum;
creditChargeInfo.PostalCode = order.BillingZip;
creditCardPayment.CreditChargeInfo = creditChargeInfo;
payment.AnyIntuitObject = creditCardPayment;
payment.TotalAmt = Convert.ToDecimal(order.TotalAmount);
payment.TotalAmtSpecified = true;
payment.UnappliedAmt = Convert.ToDecimal(order.TotalAmount);
payment.UnappliedAmtSpecified = true;
//Adding the Payment
Payment added = Helper.Add<Payment>(qboContextoAuth, payment);
return added;
}
From what I have gathered from the raw API, here is what I need:
https://developer.intuit.com/app/developer/qbpayments/docs/api/resources/all-entities/tokens
But I don't seem to be able to find such functionality in the SDK. Does anyone have experience doing this?
Here is the solution to this problem as of today (03/14/19):
public string getCardToken()
{
string cardToken="";
JObject jsonDecodedResponse;
string cardTokenJson = "";
string cardTokenEndpoint = "quickbooks/v4/payments/tokens";
string uri= paymentsBaseUrl + cardTokenEndpoint;
string cardTokenRequestBody = "{\"card\":{\"expYear\":\"2020\",\"expMonth\":\"02\",\"address\":{\"region\":\"CA\",\"postalCode\":\"94086\",\"streetAddress\":\"1130 Kifer Rd\",\"country\":\"US\",\"city\":\"Sunnyvale\"},\"name\":\"emulate=0\",\"cvc\":\"123\",\"number\":\"4111111111111111\"}}";
// send the request (token api call does not requires Authorization header, rest all payments call do)
HttpWebRequest cardTokenRequest = (HttpWebRequest)WebRequest.Create(uri);
cardTokenRequest.Method = "POST";
cardTokenRequest.ContentType = "application/json";
cardTokenRequest.Headers.Add("Request-Id", Guid.NewGuid().ToString());//assign guid
byte[] _byteVersion = Encoding.ASCII.GetBytes(cardTokenRequestBody);
cardTokenRequest.ContentLength = _byteVersion.Length;
Stream stream = cardTokenRequest.GetRequestStream();
stream.Write(_byteVersion, 0, _byteVersion.Length);
stream.Close();
// get the response
HttpWebResponse cardTokenResponse = (HttpWebResponse)cardTokenRequest.GetResponse();
using (Stream data = cardTokenResponse.GetResponseStream())
{
cardTokenJson= new StreamReader(data).ReadToEnd();
jsonDecodedResponse = JObject.Parse(cardTokenJson);
if (!string.IsNullOrEmpty(jsonDecodedResponse.TryGetString("value")))
{
cardToken = jsonDecodedResponse["value"].ToString();
}
}
return cardToken;
}
They may add an SDK option to do the same some day, but it's not available as of today!
I am trying to connect to the Google Analytics reporting API to get basic pageview stats. Im trying to follow this tutorial (http://www.arboundy.com/2012/04/getting-started-with-google-analytics-in-c/). I'm having trouble setting the correct bits to get a successful auth as it seems google has changed the APIs a lot lately so the original config doesn't seem to work.
Heres what I currently have:
Service = new AnalyticsService("MyDemoApp");
Service.setUserCredentials("user#gmail.com", "password");
AccountQuery AccountsQuery = new AccountQuery("https://www.googleapis.com/analytics/v3/data/ga"/*Not sure what goes here this gives a 400*/);
AccountFeed AccountsFeed = Service.Query(AccountsQuery); // 400 error here
Any ideas how to connect to this via the V3 api (which appears to be the one I got from NuGet)
this must work for u in c#. (i have tried and worked)
string username = "youremailuser#domain.com";
string pass = "yourpassword";
string gkey = "?key=YourAPIkEY";
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:12345678";
query1.Metrics = "ga:visits";
query1.Sort = "ga:visits";
query1.GAStartDate = new DateTime(2012, 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;
}
for more details Read data from Google data API
Here is what im trying to do , i got a webpage with signin page with cresedentials from our database , then once is logged in it should redirect you to main page where you should see the data in charts.
The problem is I used gdata v2.4 but every time i want make a request i have to set the cresedentials again, then v3.0 with oauth 2.0 it said we don't need to this anymore by access token.
I managed to make it work but the problem is if the user been asked to login with gmail account and the email and password doesnt match the profile id of the request it gives the 403 error (forbidden access) this is the code . i tried to use service account no chance , any one knows whats the problem?
log4net.Config.XmlConfigurator.Configure();
//string Scope = AnalyticsService.Scopes.Analytics.ToString().ToLower();
//string scopeUrl = "https://www.google.com/analytics/feeds/" + Scope;
string Scope = "https://www.google.com/analytics/feeds/";
const string ServiceAccountId = "xxxxxxxxxxx.apps.googleusercontent.com";
const string ServiceAccountUser = "xxxxxxxxxxx#developer.gserviceaccount.com";
string key = string.Empty;
foreach (string keyname in Directory.GetFiles(Server.MapPath("/"), "*.p12", SearchOption.AllDirectories))
{
key = keyname;
}
AssertionFlowClient client = new AssertionFlowClient(
GoogleAuthenticationServer.Description, new X509Certificate2(key, "notasecret", X509KeyStorageFlags.Exportable))
{
Scope = Scope,
ServiceAccountId = ServiceAccountUser//,ServiceAccountUser = ServiceAccountUser
};
WebServerClient myWebServerClient = new WebServerClient(GoogleAuthenticationServer.Description);
myWebServerClient.ClientIdentifier = this.ClientID;
myWebServerClient.ClientSecret = this.ClientSecret;
OAuth2Authenticator<WebServerClient> authenticator = new OAuth2Authenticator<WebServerClient>(myWebServerClient, GetAuthorization);
AnalyticsService service = new AnalyticsService(authenticator);
string profileId = Session["_ProfileID"].ToString() ;
string startDate = StartDate;
string endDate = EndDate;
string metrics = "ga:visits";
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
request.Dimensions = "ga:date";
request.StartIndex = 1;
request.MaxResults = 500;
GaData data = request.Fetch();
return data;
dont bother anymore , i got it right with offline access . Thanks for showing the SUPPORT
I am using the PayPal sandbox in ASP.Net C# 4.0. I added the following web references:
https://www.sandbox.paypal.com/wsdl/PayPalSvc.wsdl
https://www.paypalobjects.com/wsdl/PayPalSvc.wsdl
When I run this code:
PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutReq req = new PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutReq()
{
SetExpressCheckoutRequest = new PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutRequestType()
{
Version = Version,
SetExpressCheckoutRequestDetails = reqDetails
}
};
// query PayPal and get token
PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutResponseType resp = BuildPayPalSandboxWebservice().SetExpressCheckout(req);
In my resp object, the error message says:
Security header is not valid
I was told to give it correct API credentials. I signed up on developer.paypal.com and i'm assuming the email address and password i used are my valid credentials. How and where do I give it my API credentials? Thanks
Did you check the endpoint addresses in your web.config file
Those should be referenced to following url's
For API Certificate => SOAP https://api.sandbox.paypal.com/2.0/
For API Signature => SOAP https://api-3t.sandbox.paypal.com/2.0/
If you are using Signature then use the following code
CustomSecurityHeaderType type = new CustomSecurityHeaderType();
type.Credentials = new UserIdPasswordType()
{
Username = ConfigurationManager.AppSettings["PayPalUserName"], //Not paypal login username
Password = ConfigurationManager.AppSettings["PayPalPassword"], //not login password
Signature = ConfigurationManager.AppSettings["PayPalSignature"]
};
To get Paypal signature follow the link
For more info click here
Update:
Please check the following code it is working for me
CustomSecurityHeaderType type = new CustomSecurityHeaderType();
type.Credentials = new UserIdPasswordType()
{
Username = ConfigurationManager.AppSettings["PayPalUserName"],
Password = ConfigurationManager.AppSettings["PayPalPassword"],
Signature = ConfigurationManager.AppSettings["PayPalSignature"]
};
PaymentDetailsItemType[] pdItem = new PaymentDetailsItemType[1];
pdItem[0] = new PaymentDetailsItemType()
{
Amount = new BasicAmountType(){currencyID = CurrencyCodeType.USD,Value = ItemPrice},
Name = ItemName,
Number = ItemNumber,
Description = ItemDescription,
ItemURL = ItemUrl
};
SetExpressCheckoutRequestDetailsType sdt = new SetExpressCheckoutRequestDetailsType();
sdt.NoShipping = "1";
PaymentDetailsType pdt = new PaymentDetailsType()
{
OrderDescription = OrderDesc,
PaymentDetailsItem = pdItem,
OrderTotal = new BasicAmountType()
{
currencyID = CurrencyCodeType.USD,
Value = ItemPrice
}
};
sdt.PaymentDetails = new PaymentDetailsType[] { pdt };
sdt.CancelURL = "http://localhost:62744/PaymentGateway/PaymentFailure.aspx";
sdt.ReturnURL = "http://localhost:62744/PaymentGateway/ExpressCheckoutSuccess.aspx";
SetExpressCheckoutReq req = new SetExpressCheckoutReq()
{
SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
{
SetExpressCheckoutRequestDetails = sdt,
Version = "92.0"
}
};
var paypalAAInt = new PayPalAPIAAInterfaceClient();
var resp = paypalAAInt.SetExpressCheckout(ref type, req);
if (resp.Errors != null && resp.Errors.Length > 0)
{
// errors occured
throw new Exception("Exception(s) occured when calling PayPal. First exception: " +
resp.Errors[0].LongMessage);
}
Response.Redirect(string.Format("{0}?cmd=_express-checkout&token={1}",
ConfigurationManager.AppSettings["PayPalOriginalUrl"], resp.Token));